Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1401581
  • 博文数量: 842
  • 博客积分: 12411
  • 博客等级: 上将
  • 技术积分: 5772
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-14 14:43
文章分类

全部博文(842)

文章存档

2013年(157)

2012年(685)

分类:

2012-04-30 20:49:43


点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<pthread.h>
  3. #include<string.h>
  4. #include<sys/types.h>
  5. #include<unistd.h>
  6. void printids(const char *s){
  7. pid_t pid;
  8. pthread_t tid;
  9. pid = getpid();
  10. tid = pthread_self();
  11. printf("%s pid %u tid %u (0x%x)\n",s,(unsigned int)pid,(unsigned int)tid,(unsigned
  12. int)tid);
  13. }
  14. void *thr_fn1(void *arg)
  15. {
  16.         printids("new pthread:");
  17.         printf("thread 1 return \n");
  18.         return ((void *)1);
  19. }
  20. int main(void)
  21. {
  22.         int err=0;
  23.         pthread_t tid1,tid2;
  24.         void *tret;
  25.         err=pthread_create(&tid1,NULL,thr_fn1,NULL);
  26.         if(err!=0)
  27.         {
  28.                 printf("can't create\n");
  29.         }
  30.         err=pthread_join(tid1,&tret);
  31.         if(err!=0)
  32.         printf("can't join with pthread 1",strerror(err));
  33.         printf("pthread exit code %d\n",(int)tret);
  34.         printids("main pthread:");
  35.         //getchar();
  36.         sleep(1);
  37.         return 0;
  38. }

输出:
[omcbo@DGSERNMC111 Privacy]$ ./pthead
new pthread: pid 23532 tid 3078073200 (0xb777ab70)
thread 1 return
pthread exit code 1
main pthread: pid 23532 tid 3078076624 (0xb777b8d0)
 
由于pthread库不是Linux系统默认的库,连接时需要使用库libpthread.a,所以在使用pthread_create创建线程时,在编译中要加-lpthread参数:
gcc -o pthread -lpthread pthread.c
阅读(884) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~