c++条件变量通知未按预期工作

标签 c++ multithreading concurrency c++14 condition-variable

我正在尝试在之前的 worker_thread 中的工作开始 后立即启动新线程,但可能已经结束也可能没有。我用时间延迟替换了开始和结束的工作。我的代码是:

#include <iostream>
#include <string>
#include <mutex>
#include <condition_variable>
#include <future>
#include <atomic>
#include <chrono>
#include <thread>

std::mutex m;
std::condition_variable cv;
bool started = false;

void worker_thread()
{
    std::unique_lock<std::mutex> lk(m);

    static std::atomic<int> count(1);
    std::this_thread::sleep_for(std::chrono::milliseconds{(count % 5) * 100});
    std::cerr << "Start Worker thread: " << count << "\n";

    started = true;
    lk.unlock();
    cv.notify_one();

    std::this_thread::sleep_for(std::chrono::milliseconds{3000});
    std::cerr << "Exit Worker thread: " << count << "\n";
    ++count;
}

int main()
{
    while(1) {
        std::async(std::launch::async, worker_thread);
        std::unique_lock<std::mutex> lk(m);
        cv.wait(lk, []{return started;});
        started = false;
    }
}

输出看起来像这样:

Start Worker thread: 1
Exit Worker thread: 1
Start Worker thread: 2
Exit Worker thread: 2
Start Worker thread: 3
Exit Worker thread: 3
Start Worker thread: 4
Exit Worker thread: 4
Start Worker thread: 5
Exit Worker thread: 5

这不是我想要的行为。我想要的是(不完全是)这样的东西:

Start Worker thread: 1
Start Worker thread: 2
Start Worker thread: 3
Start Worker thread: 4
Exit Worker thread: 1
Exit Worker thread: 3
Exit Worker thread: 4
Exit Worker thread: 2
Start Worker thread: 5
Exit Worker thread: 5

目前下一个线程只有在前一个线程的工作完成后才会启动。但是我想在上一个线程开始工作后立即启动下一个线程,而不是等待它结束,只等待开始。

最佳答案

std::async 返回一个 std::future 保存函数执行的结果。在您的情况下,它是一个被立即销毁的临时对象。 std::future 的文档说:

these actions will not block for the shared state to become ready, except that it may block if all of the following are true:

✔ the shared state was created by a call to std::async

✔ the shared state is not yet ready

✔ this was the last reference to the shared state

所有这些都是正确的,因此对 future 的破坏将阻塞,直到 worker 函数完成执行。

你可以创建分离线程来避免这个问题:

std::thread(worker_thread).detach();

关于c++条件变量通知未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43156908/

相关文章:

java - 以并发方式逐行处理文件

c++ - 扣除指南的尾随返回类型不是特化

c++ - 向 QTabWidget 添加选项卡后 Qt App 崩溃

java - 有没有比使用 CountDownLatch 更好的等待两个线程完成任务的方法?

multithreading - 如何锁定简单的字节数组

java - 代理对象抛出 NullPointerException

c++ - 未找到命令,C++ 应用程序

c++ - 尝试从文件中读取时设置了故障位 - 为什么?

java - 实现不同步读取的双缓冲java HashMap

java - 如何利用Camel提高效率?