日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

pthread_join/pthread_exit用法实例

發布時間:2023/12/10 编程问答 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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

?

?

?

?

pthread_self, pthread_equal pthread_t pthread_self();? 獲取線程自身ID

int pthread_equal(pthread_t threadid1, pthread_t thread2)? 判斷兩個線程ID是否相等,返回0 不相等,非零相等

?

總結

以上是生活随笔為你收集整理的pthread_join/pthread_exit用法实例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。