我想知道为什么在没有执行上层代码的情况下调用函数 doWork() 。代码如下:
void doWork()
{
std::cout<<"Hello World>";
sleep(1);
doWork();
}
....
void foo()
{
std:cout<<"This is text is never seen in the console but doWork timer callback works";
std::thread thread([&]{doWork();});
}
为什么 std:cout 不工作但 std::thread 正在执行?
谢谢
最佳答案
您不刷新缓冲区。尝试添加
<< std::flush
或<< std::endl
在最后。在对象
thread
之前需要等待线程中的执行完成被破坏了。thread.join(); // Wait for thread to finish.
您不需要在 lambda (
[&]
) 中捕获所有内容作为引用。您似乎没有使用任何这些捕获。如果您使用的是可移植的 C++11
std::thread
库,不要使用特定于 Linux 的sleep
功能。而是使用std::this_thread::sleep_for
,例如:void doWork() { // (1. Flush buffer here too) std::cout << "Hello World>" << std::flush; // 4. Use portable sleep. std::this_thread::sleep_for(std::chrono::seconds(1)); doWork(); } // .... void foo() { // 1. Flush buffer. std::cout << "This text is seen in the console" << std::endl; std::thread thread([] { // 3. No need to capture everything by reference doWork(); }); thread.join(); // 2. Wait for thread to finish. }
关于c++:为什么执行回调但不执行回调定义之前的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19837248/