pthread_join函數是一個多線程編程中非常常見的函數。本文將從多個方面進行詳細闡述pthread_join函數的使用方法和注意事項。
一、pthread_join函數的使用
pthread_join函數是用來等待一個線程結束的函數,即等待參數中指定的線程執行結束後,才會繼續執行當前線程。具體使用方法如下:
int pthread_join(pthread_t thread, void **retval);
其中,第一個參數thread表示需要等待結束的線程;第二個參數retval表示線程的返回值。該函數的返回值為0表示執行成功,否則表示執行失敗。
使用pthread_join函數的典型示例如下:
#include <stdio.h> #include <pthread.h> void *myThread(void *arg) { int i; for (i = 0; i < 100; i++) { printf("Thread %ld: %d\n", pthread_self(), i); } return NULL; } int main() { pthread_t thread; pthread_create(&thread, NULL, myThread, NULL); pthread_join(thread, NULL); printf("Main thread exit.\n"); return 0; }
在該示例中,首先定義了一個線程函數myThread,該函數會列印出當前線程ID以及計數器i的值。然後在主函數中創建了一個新線程,並調用pthread_join函數等待該線程結束,最後輸出一行「Main thread exit.」。
二、pthread_join函數的注意事項
1. 多次等待同一個線程
如果在同一線程中多次調用pthread_join函數等待同一個線程結束,那麼後面的調用會覆蓋掉前面的調用,因此只會等待一次。
示例代碼如下:
pthread_t thread; pthread_create(&thread, NULL, myThread, NULL); pthread_join(thread, NULL); pthread_join(thread, NULL); // 該調用相當於無效,不會等待線程
2. 多個線程同時等待同一個線程
如果多個線程同時等待同一個線程,那麼只要有一個線程執行了pthread_join函數就可以使該線程結束。
示例代碼如下:
pthread_t thread; pthread_create(&thread, NULL, myThread, NULL); pthread_t otherThread1; pthread_create(&otherThread1, NULL, otherThread, NULL); pthread_t otherThread2; pthread_create(&otherThread2, NULL, otherThread, NULL); pthread_join(thread, NULL); // 只要有一個線程調用了pthread_join,該線程就結束
3. 線程要麼被等待,要麼被分離
如果一個線程既沒有被等待,也沒有被分離,那麼該線程在結束後並不會自動回收其資源,因此會發生內存泄漏。因此,在使用pthread_create函數創建線程時,需要指定線程的屬性為分離屬性。
示例代碼如下:
pthread_t thread; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); // 設置線程屬性為分離屬性 pthread_create(&thread, &attr, myThread, NULL); // 注意:不需要調用 pthread_join 等待線程結束 pthread_attr_destroy(&attr);
4. 堵塞線程和非堵塞線程
在(pthread_join)函數調用時,線程可以是堵塞的或非堵塞的。如果使用非堵塞的線程,線程完結後不會等待,pthread_join會直接返回。而如果是使用的堵塞的線程,則需要直到線程結束才能返回。
示例代碼如下:
pthread_t thread; pthread_create(&thread, NULL, myThread, NULL); pthread_join(thread, NULL); // 堵塞等待線程結束 pthread_t otherThread1; pthread_create(&otherThread1, NULL, otherThread, NULL); pthread_t otherThread2; pthread_create(&otherThread2, NULL, otherThread, NULL); int status = pthread_tryjoin_np(thread, NULL); if (status == 0) { printf("Thread end.\n"); } else { printf("Thread is still running.\n"); }
三、總結
本文詳細闡述了pthread_join函數的使用方法和注意事項,包括多次等待同一個線程、多個線程同時等待同一個線程、線程要麼被等待要麼被分離、以及堵塞線程和非堵塞線程等多個方面。
原創文章,作者:TDLKS,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/371013.html