基于linux下的高并发服务器开发(第三章)- 3.4 连接已终止的线程

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

>>pthread_join()

线程和进程一样子线程退出的时候其内核资源主要由主线程回收线程库中提供的线程回收函叫做pthread_join()这个函数是一个阻塞函数如果还有子线程在运行调用该函数就会阻塞子线程退出函数解除阻塞进行资源的回收函数被调用一次只能回收一个子线程如果有多个子线程则需要循环进行回收。

#include <pthread.h>
// 这是一个阻塞函数, 子线程在运行这个函数就阻塞
// 子线程退出, 函数解除阻塞, 回收对应的子线程资源, 类似于回收进程使用的函数 wait()

int pthread_join(pthread_t thread, void **retval);

参数:

        thread : 要被回收的子线程的线程ID

        retval : 二级指针, 指向一级指针的地址, 是一个传出参数, 这个地址中存储了        

                    pthread_exit() 传递出的数据如果不需要这个参数可以指定为NULL

返回值

        线程回收成功返回0回收失败返回错误号

作者: 苏丙榅
链接: https://subingwen.cn/linux/thread/
来源: 爱编程的大丙
著作权归作者所有。商业转载请联系作者获得授权非商业转载请注明出处。

#include <pthread.h>
int pthread_join(pthread_t thread, void **retval);
	- 功能和一个已经终止的线程进行连接
			回收子线程的资源
			这个函数是阻塞函数调用一次只能回收一个子线程
			一般在主线程中使用
	- 参数
		- thread需要回收的子线程的ID
		- retval: 接收子线程退出时的返回值
	- 返回值
		0 : 成功
		非0 : 失败返回的错误号

pthread_join.c

#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>

int value = 10;

void * callback(void * arg) {
    printf("child thread id : %ld\n", pthread_self());
    // sleep(3);
    // return NULL; 
    //int value = 10; // 局部变量
    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 < 5; i++) {
        printf("%d\n", i);
    }

    printf("tid : %ld, main thread id : %ld\n", tid ,pthread_self());

    // 主线程调用pthread_join()回收子线程的资源
    int* thread_retval;
    ret = pthread_join(tid,(void **)&thread_retval);
    if(ret != 0) {
        char * errstr = strerror(ret);
        printf("error : %s\n", errstr);
    }
    printf("exit data : %d\n", *thread_retval);

    printf("回收子线程资源成功\n");

    // 让主线程退出,当主线程退出时不会影响其他正常运行的线程。
    pthread_exit(NULL);

    return 0; 
}

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: linux服务器

“基于linux下的高并发服务器开发(第三章)- 3.4 连接已终止的线程” 的相关文章