pthread_join第二个参数
时间: 2023-08-13 07:05:45 浏览: 83
pthread_join函数的第二个参数是一个指针,用于获取线程的返回值。当线程执行完毕并退出时,它的返回值可以通过该指针来获取。这个参数是一个 void** 类型的指针,因为线程的返回值可以是任意类型的指针。
在调用pthread_join函数时,需要将线程的ID作为第一个参数传入,将返回值的指针作为第二个参数传入。当线程退出后,其返回值会被存储到这个指针所指向的内存中,可以通过解引用该指针来获取线程的返回值。
示例代码如下:
```c
#include <pthread.h>
#include <stdio.h>
void* thread_func(void* arg) {
int* value = (int*)arg;
int result = *value * 2;
return (void*)result;
}
int main() {
pthread_t thread;
int value = 10;
void* result;
pthread_create(&thread, NULL, thread_func, (void*)&value);
pthread_join(thread, &result);
printf("Thread returned: %d\n", (int)result);
return 0;
}
```
在上面的示例中,创建了一个新的线程,并将参数值10传递给线程函数thread_func。线程函数将参数值乘以2,并将结果作为返回值。在主线程中,使用pthread_join函数等待线程结束,并通过result指针获取到线程的返回值。最后打印出线程的返回值。
需要注意的是,在使用pthread_join函数时,必须确保目标线程已经结束,否则调用pthread_join函数将会阻塞当前线程。