pthread_join/pthread_exit用法實例

函數pthread_join用來等待一個線程的結束。函數原型爲:
  extern int pthread_join __P ((pthread_t __th, void **__thread_return));
  第一個參數爲被等待的線程標識符,第二個參數爲一個用戶定義的指針,它可以用來存儲被等待線程的返回值。這個函數是一個線程阻塞的函數,調用它的線程將一直等待到被等待的線程結束爲止,當函數返回時,被等待線程的資源被收回。一個線程的結束有兩種途徑,一種是象我們上面的例子一樣,函數結束了,調用它的線程也就結束了;另一種方式是通過函數pthread_exit來實現。它的函數原型爲:
  extern void pthread_exit __P ((void *__retval)) __attribute__ ((__noreturn__));
  唯一的參數是函數的返回代碼,只要pthread_exit中的參數retval不是NULL,這個值將被傳遞給 thread_return。最後要說明的是,一個線程不能被多個線程等待,否則第一個接收到信號的線程成功返回,其餘調用pthread_join的線程則返回錯誤代碼ESRCH。

實例:

/*myfile11-3.c*/


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

pthread_t       tid1, tid2; 
void            *tret;

 

void *
thr_fn1(void *arg)
{
        sleep(1);//睡眠一秒,等待TID2結束。
        pthread_join(tid2, &tret);//tid1一直阻賽,等到tid2的退出,獲得TID2的退出碼
         printf("thread 2 exit code %d\n", (int)tret);
    printf("thread 1 returning\n");
    return((void *)2);
}

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

int
main(void)
{
    int            err;

    err = pthread_create(&tid1, NULL, thr_fn1, NULL);
    if (err != 0)
        printf("can't create thread 1\n");
    err = pthread_create(&tid2, NULL, thr_fn2, NULL);
    if (err != 0)
        printf("can't create thread 2\n");
    err = pthread_join(tid1, &tret);//祝線程一直阻賽,等待TID1的返回。
    if (err != 0)
        printf("can't join with thread 1\n");
    printf("thread 1 exit code %d\n", (int)tret);
      //err = pthread_join(tid2, &tret);
    //if (err != 0)
    //    printf("can't join with thread 2\n");
//    printf("thread 2 exit code %d\n", (int)tret);
    exit(0);
}

 


命令:#gcc -lthread myfile11-3.c

        :#./a.out

運行結果:

thread 2 exiting
thread 2 exit code 3
thread 1 returning
thread 1 exit code 2

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章