pthread_join/pthread_exit用法实例
函數(shù)pthread_join用來等待一個線程的結束。函數(shù)原型為:
extern int pthread_join __P ((pthread_t __th, void **__thread_return));
第一個參數(shù)為被等待的線程標識符,第二個參數(shù)為一個用戶定義的指針,它可以用來存儲被等待線程的返回值。這個函數(shù)是一個線程阻塞的函數(shù),調(diào)用它的線程將一直等待到被等待的線程結束為止,當函數(shù)返回時,被等待線程的資源被收回。一個線程的結束有兩種途徑,一種是象我們上面的例子一樣,函數(shù)結束了,調(diào)用它的線程也就結束了;另一種方式是通過函數(shù)pthread_exit來實現(xiàn)。它的函數(shù)原型為:
extern void pthread_exit __P ((void *__retval)) __attribute__ ((__noreturn__));
唯一的參數(shù)是函數(shù)的返回代碼,只要pthread_exit中的參數(shù)retval不是NULL,這個值將被傳遞給 thread_return。最后要說明的是,一個線程不能被多個線程等待,否則第一個接收到信號的線程成功返回,其余調(diào)用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
?
?
?
?
pthread_self, pthread_equal pthread_t pthread_self();? 獲取線程自身IDint pthread_equal(pthread_t threadid1, pthread_t thread2)? 判斷兩個線程ID是否相等,返回0 不相等,非零相等
?
總結
以上是生活随笔為你收集整理的pthread_join/pthread_exit用法实例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ImageView及其子类
- 下一篇: 关于pragma pack的用法(一)