pthread_join
是 Linux 中用于等待一個或多個線程完成的函數
pthread_join
的主要作用如下:
確保主線程等待子線程完成:在多線程程序中,主線程可能需要在其他線程完成任務之后才能繼續執行。通過使用 pthread_join
,主線程可以阻塞自己,直到子線程完成。
獲取子線程的返回值:pthread_join
可以用來獲取子線程的返回值。當子線程完成時,pthread_join
會將子線程的返回值存儲在一個參數中,以便主線程使用。
避免死鎖:如果不使用 pthread_join
等待子線程完成,主線程可能會在子線程還在執行時結束,導致子線程成為孤兒進程。這可能導致資源泄漏和其他問題。使用 pthread_join
可以確保主線程等待子線程完成,從而避免死鎖。
下面是一個簡單的示例:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *print_hello(void *arg) {
printf("Hello from thread %ld\n", (long)arg);
pthread_exit(NULL);
}
int main() {
pthread_t threads[5];
int rc;
long t;
for (t = 0; t < 5; t++) {
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, print_hello, (void *)t);
if (rc) {
printf("ERROR: return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
for (t = 0; t < 5; t++) {
printf("In main: joining thread %ld\n", t);
rc = pthread_join(threads[t], NULL);
if (rc) {
printf("ERROR: return code from pthread_join() is %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
}
在這個示例中,主線程創建了 5 個子線程,每個子線程打印一條消息。然后,主線程使用 pthread_join
等待每個子線程完成。最后,主線程結束。