linuxでのスレッドの作成と待機


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
char message[]="hello world ";
void *thread_function(void *arg)//    
{
   printf("thread_function is running, Argument is %s
",(char *)arg); sleep(3); strcpy(message,"Bye!"); pthread_exit("Thank you for the cpu time");// } int main() { int res; pthread_t a_thread; // void *thread_result;// res=pthread_create(&a_thread,NULL,thread_function,(void *)message);// if(res!=0)// { perror("Thread create error!"); exit(EXIT_FAILURE); } printf("waiting for thread to finish...
"); res=pthread_join(a_thread,&thread_result);// if(res!=0) { perror("Thread join error!"); exit(EXIT_FAILURE); } printf("Thread joined , it returned %s
",(char *)thread_result); printf("Message is now %s
",message); exit(EXIT_SUCCESS); }

なお、マルチスレッドのコンパイルは通常のプログラムのコンパイルとは異なり、【cc-D_REENTRANT thread.c-g-o thread-lpthread】
グローバル変数messageはスレッド作成関数を介してスレッド関数に渡され、「hello world」から「Bye!」に変化していることがわかります.
 res=pthread_join(a_thread,&thread_result);//       
は、新しいスレッドが終了するのを待っています.新しいスレッドが終了した後にのみ、下に実行されます.