目录
1、连接已终止的线程(pthread_join)函数解析代码举例
2、线程的分离函数解析代码举例
3、线程取消函数解析代码举例
4、线程属性函数解析代码举例
橙色
1、连接已终止的线程(pthread_join)
函数解析
/*
#include
int pthread_join(pthread_t thread, void **retval);
- 功能:和一个已经终止的线程进行连接,从而回收子线程的资源
这个函数是阻塞函数,调用一次只能回收一个子线程
一般在主线程中使用
- 参数:
- thread:需要回收的子线程的ID
- retval: 接收子线程退出时的返回值
- 返回值:
0 : 成功
非0 : 失败,返回的错误号
*/
代码举例
#include
#include
#include
#include
int value = 10;
void * callback(void * arg) {
printf("child thread id : %ld\n", pthread_self());
// sleep(3);
// return NULL;
// int value = 10; // 局部变量,在一个进程中不同的线程划分了不同的栈空间,当子线程结束后属于子线程的栈空间就被释放掉了。
//所以后面主线程中就没办法通过pthread_join来接收子线程的返回值。所以想要接收,value必须为全局变量(不能是局部变量)
pthread_exit((void *)&value); // return (void *)&value;
}
int main() {
// 创建一个子线程
pthread_t tid;
int ret = pthread_create(&tid, NULL, callback, NULL);
if(ret != 0) {
char * errstr = strerror(ret);
printf("error : %s\n", errstr);
}
// 主线程
for(int i = 0; i |