在下面的 list 中,我希望在创建线程后立即调用 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;
}
然而,从它在屏幕上打印出来的内容来看,情况并非如此。它打印
From new thread 1
From new thread 2
....
From new thread 99
quit the main function now.
看起来 main
函数在执行命令printf("quit the main function now\n");
之前等待线程完成并退出。
你能解释一下这是为什么吗?我在这里缺少什么?
最佳答案
问题是你的线程太快了。
它能够在 main 有机会继续之前打印所有 100 个字符串。
尝试让线程变慢,您会在线程之前看到主要的 printf
。
关于c++ - 为什么我的线程不在后台运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45700977/