在Linux中,使用pthread_join()
函数可以等待一个线程完成执行并获取其返回值
#include#include #include void *my_thread(void *arg) { int *result = (int *)arg; *result = 42; // 设置线程返回值 return NULL; } int main() { pthread_t thread_id; int result; // 创建线程并传递一个指向整数的指针作为参数 if (pthread_create(&thread_id, NULL, my_thread, &result) != 0) { perror("Failed to create thread"); exit(EXIT_FAILURE); } // 等待线程完成并获取其返回值 if (pthread_join(thread_id, &result) != 0) { perror("Failed to join thread"); exit(EXIT_FAILURE); } printf("Thread returned: %d\n", result); return 0; }
在这个示例中,我们创建了一个名为my_thread
的线程函数,它接受一个指向整数的指针作为参数。在主线程中,我们使用pthread_create()
创建一个新线程,并将result
变量的地址传递给新线程。然后,我们使用pthread_join()
等待新线程完成执行,并将其返回值存储在result
变量中。最后,我们打印出新线程的返回值。