Chinaunix

标题: pthread_attr_setdetachstate和pthread_detach(pthread_self())有区别吗 [打印本页]

作者: berniechen    时间: 2008-09-11 22:43
标题: pthread_attr_setdetachstate和pthread_detach(pthread_self())有区别吗
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

void* task1(void*);
void* task2(void*);

int main()
{
    pthread_t pid1, pid2;
    pthread_attr_t attr;
    int ret;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    pthread_create(&pid1, &attr, task1, NULL);
    ret=pthread_join(pid1, NULL);
    printf("ret=%d\n", ret);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    pthread_create(&pid2, &attr, task2, NULL);
    ret=pthread_join(pid2, NULL);
    printf("ret=%d\n", ret);
    return 1;
}

void* task1(void*)
{
    printf("task1\n");
    pthread_exit(NULL);
}

void* task2(void*)
{
    pthread_detach(pthread_self());
    printf("task2\n");
    pthread_exit(NULL);
}



执行结果
ret=22
task1
task2
ret=0
第一个phread_join() 没有等待直接返回了
第二个phread_join() 等待,从返回值看执行成功了。
请大家帮忙看看
作者: berniechen    时间: 2008-09-11 22:45
我两个线程分别用pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)和pthread_detach(pthread_self())来使线程达到detach状态。
怎么第二种不好使。是我的用法有问题还是理解的不对
作者: ynchnluiti    时间: 2008-09-11 23:21
After   pthread_detach   completes,   subsequent  attempts  to  perform
       pthread_join on th will fail. If another thread is already joining  the
       thread  th  at  the  time pthread_detach is called, pthread_detach does
       nothing and leaves th in the joinable state.

主线程已经执行到pthread_jion().
作者: berniechen    时间: 2008-09-12 12:44
谢谢,我在第二个pthread_join前加上sleep(1)就可以。
网上的man和我linux里的不一样。下次要多看看
作者: MMMIX    时间: 2008-09-12 13:00
原帖由 berniechen 于 2008-9-12 12:44 发表
网上的man和我linux里的不一样。下次要多看看

查文档应该先查系统中自带的,然后再从网上搜索。千万不要反过来。




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2