Linux下线程的创建和等待


  1. #include <stdio.h>   
  2. #include <unistd.h>   
  3. #include <stdlib.h>   
  4. #include <string.h>   
  5. #include <pthread.h>   
  6. char message[]="hello world ";  
  7. void *thread_function(void *arg)//线程函数   
  8. {  
  9.    printf("thread_function is running, Argument is %s\n",(char *)arg);  
  10.    sleep(3);  
  11.    strcpy(message,"Bye!");  
  12.    pthread_exit("Thank you for the cpu time");//www.bkjia.com注意线程退出函数   
  13. }  
  14.   
  15. int main()  
  16. {  
  17.   int res;  
  18.   pthread_t a_thread; //新线程的标识符   
  19.   void *thread_result;//定义一个线程返回值   
  20.   res=pthread_create(&a_thread,NULL,thread_function,(void *)message);//创建线程   
  21.   if(res!=0)//线程创建不成功   
  22.     {  
  23.      perror("Thread create error!");  
  24.      exit(EXIT_FAILURE);  
  25.     }  
  26.   printf("waiting for thread to finish...\n");  
  27.   res=pthread_join(a_thread,&thread_result);//等待新线程结束   
  28.   if(res!=0)  
  29.    {  
  30.      perror("Thread join error!");  
  31.      exit(EXIT_FAILURE);  
  32.     }  
  33.   printf("Thread joined , it returned %s\n",(char *)thread_result);  
  34.   printf("Message is now %s\n",message);  
  35.   exit(EXIT_SUCCESS);  
  36. }  

注意,多线程的编译和普通程序的编译是不一样的,要用这样的命令: 【cc -D_REENTRANT thread.c -g -o thread -lpthread】

大家可以看到,全局变量message经过线程创建函数传递给线程函数后由【hello world】变成了【Bye!】

  1. res=pthread_join(a_thread,&thread_result);//等待新线程结束  
等待新线程结束,只有新线程结束后才会向下执行。

相关内容