pthread_join
是 Linux 中用于等待一个或多个线程完成的函数
下面是一个简单的示例,展示了如何在两个线程之间使用 pthread_join
进行同步:
#include#include #include // 线程函数 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.”。