pthread_join
函数用于等待一个或多个线程完成
#include#include #include 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
作为第二个参数,因为我们不关心线程返回的值。