主线程退出,做其他退出吗? [英] main thread exit, does other exit too?

查看:117
本文介绍了主线程退出,做其他退出吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有关于在同一进程主线程和其他线程的问题。当主函数返回,其他线程退出呢?我有些迷惑我。而我写的一些测试code,是这样的:

I have a problem about main thread and other thread in the same process. When the main function return, the other thread exit too? I have some confuse me. And I write some test code, like this:

void* test1(void *arg)
{
    unsigned int i = 0;
    while (1){
        i+=1;
    }
    return NULL;
}

void* test2(void *arg)
{
    long double i = 1.0;
    while (1){
        i *= 1.1;
    }
    return NULL;
}

void startThread ( void * (*run)(void*), void *arg) {
  pthread_t t;
  pthread_attr_t attr;
  if (pthread_attr_init(&attr) != 0
      || pthread_create(&t, &attr, run, arg) != 0
      || pthread_attr_destroy(&attr) != 0
      || pthread_detach(t) != 0) {
    printf("Unable to launch a thread\n");
    exit(1);
  }
}

int main()
{
    startThread(test1, NULL);
    startThread(test2, NULL);

    sleep(4);
    printf("main thread return.\n");

    return 0;
}

在主线程的回报。放出来,螺纹TEST1和TEST2也退出,任何人都可以告诉我为什么?

When the "main thread return." put out, thread test1 and test2 also exit, anybody can tell me why?

推荐答案

在主线程返回时,它会终止整个进程。这包括所有的其他线程。当你调用退出

When the main thread returns, it terminates the entire process. This includes all other threads. The same thing happens when you call exit.

pthread_detach 的目的是要使它所以你不需要与其他线程的加入,以释放其资源。分离一个线程不让它存在近进程终止,它仍然会与所有其他线程摧毁一起。

The purpose of pthread_detach is to make it so you don't need to join with other threads in order to release their resources. Detaching a thread does not make it exist past process termination, it will still be destroyed along with all the other threads.

这篇关于主线程退出,做其他退出吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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