linux下线程的分离和结合属性

在任何一个时间点上,线程是可结合的(joinable),或者是分离的(detached)。一个可结合的线程能够被其他线程收回其资源和杀死;在被其他线程回收之前,它的存储器资源(如栈)是不释放的。相反,一个分离的线程是不能被其他线程回收或杀死的,它的存储器资源在它终止时由系统自动释放。 

默认情况下,线程被创建成可结合的。为了避免存储器泄漏,每个可结合线程都应该要么被显示地回收,即调用pthread_join;要么通过调用pthread_detach函数被分离。如果一个可结合线程结束运⾏行但没有被join,则它的状态类似于进程中的Zombie Process, 即还有一部分资源没有被回收,所以创建线程者应该调用pthread_join来等待线程运行结束,并可得到线程的退出代码,回收其资源。 由于调用pthread_join后,如果该线程没有运行结束,调用者会被阻塞,在有些情况下我们并不希望如此。例如,在Web服务器中当主线程为每个新来的连接请求创建一个子线程进 行处理的时候,主线程并不希望因为调用pthread_join而阻塞(因为还要继续处理之后到来 的连接请求), 这时可以在子线程中加入代码:

pthread_detach(pthread_self());

或者父线程调用时加入:

pthread_detach(thread_id)

这将该子线程的状态设置为分离的(detached),如此一来,该线程运⾏行结束后会自动释 放所有资源。

代码示例:

#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<sys/types.h>

void* pthread_running(void *_val)
{ 
    pthread_detach(pthread_self());
    printf("%s\n", (char*)_val);
    return NULL;
}

int main()
{ 
    pthread_t tid;
    int ret = pthread_create(&tid, NULL, pthread_running, "main thread is running");

    if(ret != 0)
    { 
        printf("create thread error! info is:%s\n", strerror(ret));
        return ret;
    }

    int temp = 0;
    sleep(1);
    if(0 == pthread_join(tid, NULL))
    { 
        printf("pthread wait success!\n");
        temp = 0;
    }
    else
    { 
        printf("pthread wait failed!\n");
        temp = 1;
    }

    return temp;
}

运行结果:

猜你喜欢

转载自www.cnblogs.com/xiaojianliu/p/9689186.html
今日推荐