MemoryGarden's Blog

努力 -----------大能猫

C++博客 首页 新随笔 联系 聚合 管理
  118 Posts :: 11 Stories :: 20 Comments :: 0 Trackbacks
void pthread_exit(void * rval_ptr)
线程退出函数    其他线程可以通过 pthread_jion 得到这个 无类型指针 rval_ptr

int pthread_join (pthread_t tid, void **rval_ptr)
等待线程 tid 终止,调用线程将阻塞,直到 线程 tid 调用 pthrad_exit, 返回,或者被取消。 rval_ptr就是调用 exit 的参数,如果对返回值不感兴趣, 可以传递NULL

一下程序在 开启的第奇数个线程的时候,会sleep 相应的秒数,运行时,主线程由于调用 pthread_join 阻塞,可以看到标准输出会卡。


 1 #include <pthread.h>
 2 #include <unistd.h>
 3 #include <stdio.h>
 4 struct args{
 5   char name[10];
 6   int exit_code;
 7 };
 8 
 9 void * thread_run(void *arg){
10   struct args* a = (struct args*)arg;
11   printf("%s run, id:%u\n", a->name, (unsigned int)(pthread_self())); // use arg to get the params;
12   if(a->exit_code % 2){
13     sleep(a->exit_code); // make the thread sleep some second;
14     printf("im thread %d, here sleep %d second!\n", a->exit_code, a->exit_code);
15   }
16   pthread_exit((void*)(&(a->exit_code)));
17 }
18 
19 int main(){
20   pthread_t tid[10];  //thread_ids
21   struct args a[10];  //thread_function's args
22   void *ec;           //exit code
23   int i;
24   for(i = 0; i < 10++i){
25     a[i].name[0= '\0';
26     sprintf(a[i].name, "thread_%d", i);
27     a[i].exit_code = i;
28     if(pthread_create(&tid[i], NULL, thread_run, (void *)(&a[i]))){ //call pthread_create to create a thread use arg[i]
29       printf("error");
30       return 0;
31     }
32   }
33   for(i = 0; i < 10++i){
34     pthread_join(tid[i], &ec);//wait for thread tid[i] stop;
35     printf("%s exit code is:%d\n", a[i].name, (*(int*)ec));
36   }
37   return 0;
38 }
39             

编译 :
g++ ./pthread_exit.cpp -lpthread -opthread_exit

结果:
thread_0 run, id:968255760
thread_2 run, id:
951470352
thread_1 run, id:
959863056
thread_3 run, id:
943077648
thread_4 run, id:
934684944
thread_5 run, id:
926292240
thread_6 run, id:
917899536
thread_7 run, id:
909506832
thread_8 run, id:
901114128
thread_9 run, id:
892721424
thread_0 exit code 
is:0
im thread 
1, here sleep 1 second!
thread_1 exit code 
is:1
thread_2 exit code 
is:2
im thread 
3, here sleep 3 second!
thread_3 exit code 
is:3
thread_4 exit code 
is:4
im thread 
5, here sleep 5 second!
thread_5 exit code 
is:5
thread_6 exit code 
is:6
im thread 
7, here sleep 7 second!
thread_7 exit code 
is:7
thread_8 exit code 
is:8
im thread 
9, here sleep 9 second!
thread_9 exit code 
is:9






posted on 2011-06-07 00:07 memorygarden 阅读(2703) 评论(0)  编辑 收藏 引用 所属分类: 网络编程

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理