运行下面这些代码后会发生什么?
#include <thread>
#include <chrono>
#include <functional>
#include <fstream>
using namespace std;
void func()
{
std::this_thread::sleep_for(std::chrono::seconds(5));
ofstream outfile("test.txt");
outfile << "hello world" << endl;
outfile.close();
}
void start()
{
std::thread th(std::bind(func));
if (th.joinable())
th.detach();
}
int main()
{
start();
return 0;
}
结果将不会在磁盘中创建"test.txt"文件。为什么?
此外,如果我在func()中使用start()函数中新的堆数据,是否有问题?操作系统将删除它时,主线程返回,但子线程仍在运行?
正如@Brandon在评论中指出的那样,你的线程很可能没有机会运行。main()
调用构建线程的start()
,然后返回main()
,然后退出。即使是,如果你的线程有机会在这段时间内运行,你在那里设置一个5s的睡眠。
在终止程序之前需要等待线程完成。您可以使用std::thread::join
:
void start()
{
std::thread th(std::bind(func));
// if the thread was successfully created
if (th.joinable())
// wait for it to finish
th.join();
}
如果你不需要完全等待你的线程,你也可以考虑std::condition_variable
,你的线程可以在它的一些工作完成时提醒你。