设为首页收藏本站

LUPA开源社区

 找回密码
 注册
文章 帖子 博客

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

2012-2-27 10:59| 发布者: 红黑魂| 查看: 3466| 评论: 0|来自: csdn博客

摘要: 和多进程一样,多线程也有自己的等待函数。这个等待函数就是pthread_join函数。那么这个函数有什么用呢?我们其实可以用它来等待线程运行结束。view plaincopy#includestdio.h#includepthread.h#includeunistd.h#inc ...

 和多进程一样,多线程也有自己的等待函数。这个等待函数就是pthread_join函数。

那么这个函数有什么用呢?我们其实可以用它来等待线程运行结束。

  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即可。

  1. [test@localhost thread]$ ./thread  
  2. this is func!  
  3. this is end of main!  

酷毙
1

雷人

鲜花

鸡蛋

漂亮

刚表态过的朋友 (1 人)

  • 快毕业了,没工作经验,
    找份工作好难啊?
    赶紧去人才芯片公司磨练吧!!

最新评论

关于LUPA|人才芯片工程|人才招聘|LUPA认证|LUPA教育|LUPA开源社区 ( 浙B2-20090187 浙公网安备 33010602006705号   

返回顶部