Chinaunix首页 | 论坛 | 博客
  • 博客访问: 536478
  • 博文数量: 67
  • 博客积分: 1625
  • 博客等级: 上尉
  • 技术积分: 1053
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-04 14:40
文章分类

全部博文(67)

文章存档

2012年(67)

分类: LINUX

2012-04-19 18:32:05

作者:kangear

 

书籍:《UNIX环境高级编程》以下简称《UNIX书》

             C程序设计(第三版)》以下简称《C书》

 

这个也是《UNIX书》上的实例的删减版:

thread_exit.c

传源文件: thread_exit.zip   

点击(此处)折叠或打开

  1. #include <stdio.h> //printf()
  2. #include <pthread.h> //pthread_create() pthread_join() pthread_exit()
  3. #include <unistd.h> //sleep()

  4. void *create(void *arg)
  5. {
  6.     printf("new thread is created ... \n");
  7.     return (void *)8;
  8. }

  9. int main(int argc,char *argv[]) //主进程
  10. {
  11.     pthread_t tid;
  12.     int error;
  13.     void *temp;

  14.     error = pthread_create(&tid, NULL, create, NULL); //创建线程(线程处于就绪态)
  15.     printf("main thread!\n");

  16.     if( error )
  17.     {
  18.         printf("thread is not created ... \n");
  19.         return -1;
  20.     }
  21.     error = pthread_join(tid, &temp); //线程从这里开始运行 至结束

  22.     if( error )
  23.     {
  24.         printf("thread is not exit ... \n");
  25.         return -2;
  26.     }
  27.     
  28.     printf("thread is exit code %d \n", (int )temp); //线程结束后的主进程的打印
  29.     return 0;
  30. }


 

运行结果:

tu

 

(《UNIX书》原文)可以看出,当一个线程通过调用pthread_exit退出或者简单地从启动例程中返回时,进程的七大线程可以通过调用pthread_join函数获得该线程的退出状态。

 

 

pthread_join(pthread_t thread, void **rval_ptr)

 

rval_ptr

就像《非诚勿扰》里边的男嘉宾,只为9号(pthread_exit())而来,正常情况下就是用作退出用的。

阅读(7419) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~