c++ 11 std::thread使用ofstream输出的东西,但是什么也得不到,为什么?
c++ 11 std::thread use ofstream output stuff, but get nothing, why?
运行下面这些代码后会发生什么?
#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
,你的线程可以在它的一些工作完成时提醒你。
相关文章:
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 初始化或分配空字符串文字到指向 C 中的 char 的指针或指向 C++ 中 const char 的指针的原因是什么
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- 是什么导致了这种使用三进制而不是短整型的有符号int到无符号int转换
- 是否总是可以将使用递归编写的程序重写为不使用递归的程序C++,性能观点是什么?
- C++关于指针和使用函数将它们启动到堆的行为究竟是什么?
- 静态自动 constexpr t = { "red" , "black" , "green" } 是什么类型;派生到?
- 十进制到二进制的实现不能完全适用于我大学的检查器。问题或提示可能是什么
- 测试使用visual studio编写的C++android应用程序的最佳方法是什么.不升级到windows专业版
- "number>>1"在"binary(number >> 1)"中是什么意思(十进制到二进制转换)
- 引用到引用在C++中是什么意思?(不是右值引用)
- {1, 2} 是值吗?如果是,它的类型是什么?如果不是,为什么可以将其分配给初始值设定项列表
- 是什么原因导致clang找不到无序映射标头
- 找不到究竟是什么 boost::async
- 在iOS中使用Objective-C背后的哲学是什么?为什么不使用c++呢?
- c++ 11 std::thread使用ofstream输出的东西,但是什么也得不到,为什么?
- c++内部可以表示的0到1之间不舍入的最大和最小的数是什么?
- 有什么事情c++可以做得比D更好,或者D做不到的吗?(多重继承的例子)
- 我怎么知道是什么使不完整类型不完整的错误:对指向不完整类型的指针进行算术运算
- 不允许绑定到初始化列表中的引用的临时存在于actor结束之后的理由是什么?