pthread_detach问题 [英] pthread_detach question

查看:193
本文介绍了pthread_detach问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

截至目前,我是IM pression,如果你产卵后分离一个线程下,线程生活在主线程终止后还是一样。

但是,一个小实验(见下表)去违背了我的信念。我预计分离线程保持印刷,甚至主要结束之后,从分离线程说起,但这似乎并没有发生。该应用程序显然终止...

做主的问题后超然的线程在返回0

 的#include< pthreads.h中>
#包括LT&;&stdio.h中GT;void *的FUNC(void *的数据)
{
    而(1)
    {
        的printf(从分离线程... \\ n说起);
        睡眠(5);
    }
    了pthread_exit(NULL);
}诠释的main()
{
    的pthread_t手柄;
    如果(!在pthread_create(安培;手柄,NULL,FUNC,NULL))
    {
        的printf(线程成功创建!\\ n);
        如果(!pthread_detach(句柄))
            的printf(线程成功分离!\\ n);
    }    睡眠(5);
    的printf(主线程奄奄一息...... \\ n);
    返回0;
}


解决方案

要引用的的Linux程序员手册


  

分离的属性仅仅是
  决定了系统的行为
  当线程终止;它
  没有prevent被线程
  如果该过程终止终止
  使用退出(3)(或者,如果
  主线程返回)。


同样来自的Linux程序员手册 p>

  

要允许其他线程继续
  执行,主线程应该
  通过调用了pthread_exit()终止
  而不是退出(3)


Till recently, I was under the impression that if you "detach" a thread after spawning it, the thread lives even after the "main" thread terminates.

But a little experiment (listed below) goes contrary to my belief. I expected the detached thread to keep printing "Speaking from the detached thread" even after main terminated, but this does not seem to be happening. The application apparently terminates...

Do the "detached" threads die after "main" issues return 0?

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

void *func(void *data)
{
    while (1)
    {
        printf("Speaking from the detached thread...\n");
        sleep(5);
    }
    pthread_exit(NULL);
}

int main()
{
    pthread_t handle;
    if (!pthread_create(&handle, NULL, func, NULL))
    {
        printf("Thread create successfully !!!\n");
        if ( ! pthread_detach(handle) )
            printf("Thread detached successfully !!!\n");
    }

    sleep(5);
    printf("Main thread dying...\n");
    return 0;
}

解决方案

To quote the Linux Programmer's Manual:

The detached attribute merely determines the behavior of the system when the thread terminates; it does not prevent the thread from being terminated if the process terminates using exit(3) (or equivalently, if the main thread returns).

Also from the Linux Programmer's Manual:

To allow other threads to continue execution, the main thread should terminate by calling pthread_exit() rather than exit(3).

这篇关于pthread_detach问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆