当主线程退出时,其他线程是否也退出? [英] When the main thread exits, do other threads also exit?

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

问题描述

我对同一进程中的主线程和其他线程有疑问.当 main 函数返回时,其他线程是否也退出?我对此感到困惑.

I have a problem about main threads and other threads in the same process. When the main function returns, do the other threads exit too? I am confused about 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
");
    exit(1);
  }
}

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

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

    return 0;
}

当主线程返回"时.打印出来,线程test1和test2也退出了,谁能告诉我为什么?

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

推荐答案

当主线程返回时(即从 main 函数返回),它终止整个进程.这包括所有其他线程.当您调用 exit 时会发生同样的事情.您可以通过调用 pthread_exit 来避免这种情况.

When the main thread returns (i.e., you return from the main function), it terminates the entire process. This includes all other threads. The same thing happens when you call exit. You can avoid this by calling pthread_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天全站免登陆