c++:为什么执行回调但不执行回调定义之前的函数?

标签 c++ multithreading c++11 callback boost-thread

我想知道为什么在没有执行上层代码的情况下调用函数 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 正在执行?

谢谢

最佳答案

  1. 您不刷新缓冲区。尝试添加 << std::flush<< std::endl在最后。

  2. 在对象thread之前需要等待线程中的执行完成被破坏了。

    thread.join(); // Wait for thread to finish.
    
  3. 您不需要在 lambda ( [&] ) 中捕获所有内容作为引用。您似乎没有使用任何这些捕获。

  4. 如果您使用的是可移植的 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/

相关文章:

c++ - 使用适用于 C++ 的 Google 测试 API 通过参数化单元测试来测试私有(private)方法有哪些可能的方法?

c++ - 为什么我在读取二进制文本时会得到 unicodeand 大数字?

c++ - 令人困惑的内存重新排序行为

java - 多线程似乎不起作用

c++ - 将解密后的数据暂存在内存中

multithreading - C++ 11条件变量

c++ - 在构造函数初始化列表上 move shared_ptr

c++ - 如何在 C++/OpenGL 中获取当前鼠标位置?

c++ - 如何将比较运算符应用于两个匿名结构中的每个变量?

java - 组合 putIfAbsent 和替换为 ConcurrentMap 的原子性