pthread_join
函數用于等待一個或多個線程完成
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *thread_function(void *arg);
int main() {
pthread_t thread1, thread2;
int result1, result2;
// 創建第一個線程
if (pthread_create(&thread1, NULL, thread_function, (void *)1) != 0) {
perror("Error creating thread 1");
exit(EXIT_FAILURE);
}
// 創建第二個線程
if (pthread_create(&thread2, NULL, thread_function, (void *)2) != 0) {
perror("Error creating thread 2");
exit(EXIT_FAILURE);
}
// 等待第一個線程完成
result1 = pthread_join(thread1, NULL);
if (result1 != 0) {
perror("Error joining thread 1");
exit(EXIT_FAILURE);
}
// 等待第二個線程完成
result2 = pthread_join(thread2, NULL);
if (result2 != 0) {
perror("Error joining thread 2");
exit(EXIT_FAILURE);
}
printf("Both threads have finished.\n");
return 0;
}
void *thread_function(void *arg) {
int thread_id = *(int *)arg;
printf("Thread %d is running.\n", thread_id);
return NULL;
}
在這個示例中,我們創建了兩個線程,并將它們分別與整數 1
和 2
關聯。pthread_join
函數的第一個參數是要等待的線程的標識符(在這里是 thread1
和 thread2
),第二個參數是一個指向指針的指針,該指針將存儲線程返回的值。在這個例子中,我們傳遞 NULL
作為第二個參數,因為我們不關心線程返回的值。