#include <stdio.h>
#include <pthread.h>
void *thread_func(void *param)
{
int pid;
int i;
pthread_t thread_id;
thread_id = pthread_self();
printf("%s called\n", __FUNCTION__);
printf(" thread ID = %ld\n", thread_id);
printf(" 2:pid = %d\n", pid);
pid = getpid();
sleep(5);
printf(" done\n");
}
int main(void)
{
pthread_t thread;
int pid;
pid = getpid();
printf("1:pid = %d\n", pid);
if (pthread_create(&thread, NULL, thread_func, NULL) != 0) {
printf("Failed pthread_create()\n");
return -1;
}
printf("Next line of pthread_create() called. thead ID = %ld\n", thread);
pthread_join(thread, NULL);
printf("End of the program\n");
return 0;
}
出力結果
1:pid = 4780 Next line of pthread_create() called. thead ID = 7078224 thread_func called thread ID = 7078224 2:pid = 7078224 done End of the programmain() 関数から pthread_create() により thread_func が別スレッドとして生成される。
親スレッドは pthread_join() で子スレッドが終了してくるのを待つ。
0 件のコメント:
コメントを投稿