pthread_join函数的代码
时间: 2023-09-13 10:08:12 浏览: 44
下面是 `pthread_join()` 函数的代码示例:
```c
#include <pthread.h>
int pthread_join(pthread_t thread, void **retval);
```
该函数用于等待指定的线程 `thread` 结束,并接收其返回值。如果线程已经结束,则该函数会立即返回。如果线程还未结束,则调用线程会阻塞,直到被等待的线程结束。
参数说明:
- `thread`:等待的线程id。
- `retval`:指向指针的指针,用于接收被等待线程的返回值。如果不需要返回值,则可以将 `retval` 参数设置为 `NULL`。
返回值:
- 如果成功,则返回0。
- 如果发生错误,则返回错误代码。
示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *thread_func(void *arg) {
int *ret = malloc(sizeof(int));
*ret = 123;
pthread_exit(ret);
}
int main() {
pthread_t tid;
int *ret;
if (pthread_create(&tid, NULL, thread_func, NULL) != 0) {
printf("Failed to create a new thread.\n");
return 1;
}
if (pthread_join(tid, (void **)&ret) != 0) {
printf("Failed to join the thread.\n");
return 1;
}
printf("Thread returned: %d\n", *ret);
free(ret);
return 0;
}
```
在上面的示例中,我们创建了一个新线程,并等待它结束。该线程返回一个整数值,并通过 `retval` 参数传递给了主线程。最后,主线程打印出该值,并释放了 `ret` 指向的内存空间。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)