【发布时间】:2017-08-15 20:24:24
【问题描述】:
在下面的清单中,我希望当我在创建线程的行之后调用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"); 并退出之前一直等到线程完成。
你能解释一下为什么吗?我在这里缺少什么?
【问题讨论】:
-
将 100 增加到几千,看看会发生什么。话虽如此,当我在 ideone 上对其进行测试时,该线程从未打印任何内容。
-
仅仅因为你启动了一个线程,没有任何东西可以保证它会并行运行——它可能相对于你的主线程完全串行执行并且仍然是一个完全有效的线程(例如一个不经常切换任务/线程的单个 cpu 机器)。不要假设您无法保证的事情(如并发)。
标签: c++ multithreading c++11 parallel-processing