C ++条件变量通知无法按预期工作 [英] c++ condition variable notification not working as expected

查看:92
本文介绍了C ++条件变量通知无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

开始中,我正在尝试启动新线程,但是也许没有结束.我已经将开始和结束工作替换为时间延迟了.我的代码是:

I'm trying to launch new threads as soon as work in previous worker_thread has started, but maybe ended or not. I've replaced started and ended work with time delays. My code is:

#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

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

which isn't the behavior I wanted. What I wanted was something like (not exactly) this:

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

当前,下一个线程仅在前一个线程中的工作完成时才启动.但是我想在上一个线程中开始工作时立即开始下一个线程,而不是等待它结束,而仅等待开始.

Currently the next thread is only started when work is finished in previous thread. But I want to start next thread as soon as work is started in previous thread and not wait for it's end, only wait for start.

推荐答案

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

std::async returns a std::future holding result of function execution. In your case, it is a temporary object which is immideatly destroyed. The documentation for std::future says:

这些操作不会阻止共享状态变为就绪状态,除了如果满足以下所有条件,它可能会被阻止:

✔共享状态是通过调用std :: async

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

✔共享状态尚未准备好

✔这是对共享状态的最后引用

✔ this was the last reference to the shared state

所有这些都是正确的,因此对该future的销毁将阻止,直到辅助函数完成执行为止.

All of those are true, so destruction of that future will block until worker function will finish executing.

您可以创建分离的线程来避免此问题:

You can create detached thread to avoid this problem:

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

这篇关于C ++条件变量通知无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆