linux下的C语言开发(线程等待)

来源:互联网 发布:根据小说改编的网络剧 编辑:程序博客网 时间:2024/04/30 07:44

和多进程一样,多线程也有自己的等待函数。这个等待函数就是pthread_join函数。那么这个函数有什么用呢?我们其实可以用它来等待线程运行结束。

[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3. #include <unistd.h>  
  4. #include <stdlib.h>  
  5.   
  6. void func(void* args)  
  7. {  
  8.     sleep(2);  
  9.     printf("this is func!\n");  
  10. }  
  11.   
  12. int main()  
  13. {  
  14.     pthread_t pid;  
  15.   
  16.     if(pthread_create(&pid, NULL, func, NULL))  
  17.     {  
  18.         return -1;  
  19.     }  
  20.   
  21.     pthread_join(pid, NULL);  
  22.     printf("this is end of main!\n");  
  23.   
  24.     return 0;  
  25. }  

    编写wait.c文件结束之后,我们就可以开始编译了。首先你需要输入gcc wait.c -o wait -lpthread,编译之后你就可以看到wait可执行文件,输入./wait即可。

[cpp] view plaincopy
  1. [test@localhost thread]$ ./thread  
  2. this is func!  
  3. this is end of main!  
原创粉丝点击