pthread_join
是 Linux 中用于等待一個或多個線程完成的函數
下面是一個簡單的示例,展示了如何在兩個線程之間使用 pthread_join
進行同步:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
// 線程函數
void *thread_function(void *arg) {
int thread_id = *(int *)arg;
printf("Thread %d is running.\n", thread_id);
sleep(1); // 模擬線程執行耗時任務
printf("Thread %d is done.\n", thread_id);
return NULL;
}
int main() {
pthread_t thread1, thread2;
int thread_ids[2];
// 創建第一個線程
if (pthread_create(&thread1, NULL, thread_function, (void *)&thread_ids[0]) != 0) {
perror("Failed to create thread 1");
exit(EXIT_FAILURE);
}
// 創建第二個線程
if (pthread_create(&thread2, NULL, thread_function, (void *)&thread_ids[1]) != 0) {
perror("Failed to create thread 2");
exit(EXIT_FAILURE);
}
// 等待第一個線程完成
printf("Waiting for thread 1 to finish...\n");
pthread_join(thread1, NULL);
// 等待第二個線程完成
printf("Waiting for thread 2 to finish...\n");
pthread_join(thread2, NULL);
printf("All threads have finished.\n");
return 0;
}
在這個示例中,我們創建了兩個線程,并將它們的 ID 傳遞給它們。主線程等待這兩個線程完成,然后繼續執行。輸出結果如下:
Thread 0 is running.
Thread 1 is running.
Waiting for thread 1 to finish...
Thread 1 is done.
Waiting for thread 2 to finish...
Thread 0 is done.
All threads have finished.
注意,pthread_join
會阻塞主線程,直到對應的線程完成。在這個例子中,主線程在 pthread_join
之后繼續執行,打印 “All threads have finished.”。