为什么我的线程不能在后台运行?

rud*_*dky 5 c++ parallel-processing multithreading c++11

在上市波纹管,我希望当我打电话t.detach()时创建线程行之后,该线程t将在后台运行,而printf("quit the main function now \n")会叫,然后main将退出.

#include <thread>
#include <iostream>

void hello3(int* i)
{

    for (int j = 0; j < 100; j++)
    {
        *i = *i + 1;
        printf("From new thread %d \n", *i);
        fflush(stdout);

    }

    char c = getchar();
 }

int main()
{
    int i;
    i = 0;
    std::thread t(hello3, &i);
    t.detach();
    printf("quit the main function now \n");
    fflush(stdout);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

然而,从它在屏幕上打印的内容来看并非如此.它打印

From new thread 1
From new thread 2
....
From new thread 99
quit the main function now.
Run Code Online (Sandbox Code Playgroud)

看起来该main函数在执行命令printf("quit the main function now \n");并退出之前等待线程完成.

你能解释它为什么吗?我在这里缺少什么?

gsa*_*ras 3

它会根据您的操作系统调度而发生。此外,线程的速度也会影响输出。如果您停止线程(例如将 100 更改为 500),您将首先看到该消息。

我刚刚执行了代码和“立即退出主函数”。消息首先出现,如下所示:

quit the main function now 
From new thread 1 
From new thread 2 
From new thread 3 
From new thread 4 
...
Run Code Online (Sandbox Code Playgroud)

你是对的detach

将对象表示的线程与调用线程分离,允许它们彼此独立执行。

但这并不能保证“立即退出主函数”消息会首先出现,尽管很有可能。