pthreads 튜토리얼
pthreads 시작하기
수색…
비고
이 절에서는 pthread가 무엇인지, 왜 개발자가 그것을 사용하고 싶어하는지에 대한 개요를 제공합니다.
또한 pthreads 내의 큰 주제를 언급하고 관련 주제와 연결됩니다. pthreads에 대한 문서는 새로운 것이므로 관련 주제의 초기 버전을 만들어야 할 수도 있습니다.
설치 또는 설정
pthreads 설치 또는 설치에 대한 자세한 지침.
최소한의 "Hello World"와 pthreads
#include <pthread.h>
#include <stdio.h>
#include <string.h>
/* function to be run as a thread always must have the same signature:
it has one void* parameter and returns void */
void *threadfunction(void *arg)
{
printf("Hello, World!\n"); /*printf() is specified as thread-safe as of C11*/
return 0;
}
int main(void)
{
pthread_t thread;
int createerror = pthread_create(&thread, NULL, threadfunction, NULL);
/*creates a new thread with default attributes and NULL passed as the argument to the start routine*/
if (!createerror) /*check whether the thread creation was successful*/
{
pthread_join(thread, NULL); /*wait until the created thread terminates*/
return 0;
}
fprintf("%s\n", strerror(createerror), stderr);
return 1;
}
스레드에 인수 전달
#include <stdio.h>
#include <pthread.h>
void *thread_func(void *arg)
{
printf("I am thread #%d\n", *(int *)arg);
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t t1, t2;
int i = 1;
int j = 2;
/* Create 2 threads t1 and t2 with default attributes which will execute
function "thread_func()" in their own contexts with specified arguments. */
pthread_create(&t1, NULL, &thread_func, &i);
pthread_create(&t2, NULL, &thread_func, &j);
/* This makes the main thread wait on the death of t1 and t2. */
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("In main thread\n");
return 0;
}
컴파일하는 방법 :
$ gcc -pthread -o hello hello.c
인쇄 내용 :
I am thread #1
I am thread #2
In main thread
스레드에서 결과 반환 중
void * 로 변환 된 구체적인 데이터 형식에 대한 포인터를 사용하여 스레드 함수에 값을 전달하고 결과를 반환 할 수 있습니다.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
struct thread_args
{
int a;
double b;
};
struct thread_result
{
long x;
double y;
};
void *thread_func(void *args_void)
{
struct thread_args *args = args_void;
/* The thread cannot return a pointer to a local variable */
struct thread_result *res = malloc(sizeof *res);
res->x = 10 + args->a;
res->y = args->a * args->b;
return res;
}
int main()
{
pthread_t threadL;
struct thread_args in = { .a = 10, .b = 3.141592653 };
void *out_void;
struct thread_result *out;
pthread_create(&threadL, NULL, thread_func, &in);
pthread_join(threadL, &out_void);
out = out_void;
printf("out -> x = %ld\tout -> b = %f\n", out->x, out->y);
free(out);
return 0;
}
많은 경우에 이런 식으로 반환 값을 전달할 필요가 없습니다. 예를 들어 인수 struct의 공백을 사용하여 결과를 반환하거나 공유 데이터 구조에 대한 포인터를 스레드에 전달하고 거기에 저장된 결과 .
Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow