pthread_ join —— 连接已终止的线程

<aside> 💡 pthread_join 用于和一个已经终止的线程进行连接

</aside>

使用场景:当需要确保一个线程完成任务后才能继续执行,或者需要获取线程的返回值时

主线程与子线程连接,负责子线程资源的释放

pthread_join是阻塞函数,且一次调用只能回收一个子线程

Untitled

参数

返回值

例子

#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());
    // int value = 10; // 不能返回一个指向局部变量的指针

		// 将 &value 转换为 void * 类型返回
    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; 
}

pthread_detach——线程的分离

<aside> 💡 pthread_detach 用于分离线程。被分离的线程在终止的时候,会自动释放资源返回给系统

</aside>

使用场景:当不需要获取线程返回值,且不关心线程何时结束时