pthread_join()和pthread_detach()的区别

pthread_join()

有时候我们想在一个线程中等待另一个线程结束,pthread_join()则为我们提供了这个功能。例如,我们在main线程中创建了子线程,需要先等待子线程退出,最后才从main函数退出。代码如下:

void* threadFun(void* arg)
{
    printf("child thread\n");
}

int main()
{
    pthread_t t;
    if(pthread_create(&t, NULL, threadFun, NULL) != 0) {
        fprintf(stderr, "create thread fail\n");
        exit(-1);
    }

    if(pthread_join(t, NULL) != 0) {
        fprintf(stderr, "thread join fail\n");
        exit(-1);
    }

    printf("main thread exit\n");

    exit(0);
}

使用pthread_join的理由如下
一个线程终止后,如果没有别的线程对它join,那么该终止线程占用的资源,系统将无法回收,也叫作僵尸线程。因此,我们去join某个线程,意思是告诉操作系统,这个线程终止后的资源可以回收了

pthread_detach()

与pthread_join()不同,pthread_detach()的作用是分离某个线程:被分离的线程终止后,系统能自动回收该线程占用的资源

void* threadFun(void* arg)
{
    printf("child thread\n");
}

int main()
{
    pthread_t t;
    if(pthread_create(&t, NULL, threadFun, NULL) != 0) {
        fprintf(stderr, "create thread fail\n");
        exit(-1);
    }   

    if(pthread_detach(t) != 0) {
        fprintf(stderr, "thread join fail\n");
        exit(-1);
    }   

    printf("child thread exit\n");
    sleep(1);

    exit(0);
}

总结

综上,pthread_join()和pthread_detach()的区别就是:
1. pthread_join()是阻塞式的,线程A连接(join)了线程B,那么线程A会阻塞在pthread_join()这个函数调用,直到线程B终止
2. pthread_detach()是非阻塞式的,线程A分离(detach)了线程B,那么线程A不会阻塞在pthread_detach(),pthread_detach()会直接返回,线程B终止后会被操作系统自动回收资源

注意

需要注意的是一个线程被detach后就不能被join

猜你喜欢

转载自blog.csdn.net/zhwenx3/article/details/82229509