Chinaunix首页 | 论坛 | 博客
  • 博客访问: 116560
  • 博文数量: 29
  • 博客积分: 1215
  • 博客等级: 中尉
  • 技术积分: 305
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-05 16:29
文章分类
文章存档

2010年(29)

我的朋友

分类: C/C++

2010-12-07 14:02:52

预备知识:
1.线程创建函数:
       #include

       int pthread_create(pthread_t *restrict thread,
              const pthread_attr_t *restrict attr,
              void *(*start_routine)(void*), void *restrict arg);
2.线程终止函数(pthread_exit - thread termination):
       #include

       void pthread_exit(void *value_ptr);
The pthread_exit() function shall terminate the calling thread and make the value value_ptr available to any successful join with the terminating thread.
3.等待线程终止函数(pthread_join - wait for thread termination):
       #include

       int pthread_join(pthread_t thread, void **value_ptr);
       The  pthread_join()  function shall suspend execution of the calling thread until
       the target thread terminates, unless the target thread has already terminated. On
       return  from a successful pthread_join() call with a non-NULL value_ptr argument,
       the value passed to pthread_exit() by the terminating thread shall be made avail-
       able  in the location referenced by value_ptr. When a pthread_join() returns suc-
       cessfully, the target thread has been terminated.

下面编写一程序,说明如何获得已终止的线程的退出码。
程序清单:

#include <stdio.h>
#include <stdlib.h>
#inlcude <pthread.h>

void * thr_fn1(void *arg)
{
    printf("Thread 1 returning.\n");
    return ((void *)1);    
}

void * thr_fun2(void *arg)
{
    printf("thread 2 exiting.\n");
    pthread_exit((void *)2);    
}

int main(int argc,char *argv[])
{
    int rtn;
    pthread_t tid1,tid2;
    void *tret;
    
    rtn = pthread_create(&tid1,NULL,thr_fn1,NULL);
    if(rtn != 0)
    {
        printf("Can't create thread 1:%s\n",strerror(rtn));
        exit(1);
    }
    
    rtn = pthread_create(&tid2,NULL,thr_fun2,NULL);    
    if(rtn != 0)
    {
        printf("Can't create thread 2:%s\n",strerror(rtn));
        exit(1);    
    }
    
    rtn = pthread_join(tid1,&tret);
    if(rtn != 0)
    {
        printf("Can't join with thread 1:%s\n",strerror(rtn));
        exit(1);
    }
    printf("Thread 1 exit code:%d\n",(int)tret);
    
    rtn = pthread_join(tid2,&tret);
    if(rtn != 0)
    {
        printf("Can't join with thread 2:%s\n",strerror(rtn));
        exit(1);
    }
    printf("Thread 2 exit code:%d\n",(int)tret);
    
    exit(0);
}

编译源程序:
      gcc -o target.o target.c
执行程序:
    ./target
执行结果:
Thread 1 returning.
Thread 1 exit code:1
thread 2 exiting.
Thread 2 exit code:2
可见,当一个线程通过调用pthread_exit退出或者简单地从启动例程中返回时,进程中的其他线程可以通过调用pthread_join函数获得该线程的退出状态。
阅读(1829) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-12-08 14:57:02

很好的, 收藏了 推荐一个博客,提供很多免费软件编程电子书下载: http://free-ebooks.appspot.com