使用condition_variable控制多线程流 [英] Control multithreaded flow with condition_variable

查看:137
本文介绍了使用condition_variable控制多线程流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还没有把头放在C ++ 11多线程上,但是我试图让多个线程等到主线程上的某个事件再全部继续(处理发生的事情),然后当它们完成处理后,再次wait循环播放直到它们被关闭.下面不完全是-这是我的问题的更简单再现:

I haven't wrapped my head around the C++11 multithreading stuff yet, but I'm trying to have multiple threads wait until some event on the main thread and then all continue at once (processing what happened), and wait again when they're done processing... looping until they're shut down. Below isn't exactly that - it's a simpler reproduction of my problem:

std::mutex mutex;
std::condition_variable cv;

std::thread thread1([&](){ std::unique_lock<std::mutex> lock(mutex); cv.wait(lock);  std::cout << "GO1!\n"; });
std::thread thread2([&](){ std::unique_lock<std::mutex> lock(mutex); cv.wait(lock);  std::cout << "GO2!\n"; });

cv.notify_all(); // Something happened - the threads can now process it

thread1.join();
thread2.join();

这有效...除非我在某些断点处停止并放慢速度.当我这样做时,我看到Go1!,然后挂起,等待thread2cv.wait.怎么了?

This works... unless I stop on some breakpoints and slow things down. When I do that I see Go1! and then hang, waiting for thread2's cv.wait. What wrong?

也许我无论如何都不应该使用条件变量... wait周围没有任何条件,也没有需要使用互斥量保护的数据.我该怎么办?

Maybe I shouldn't be using a condition variable anyway... there isn't any condition around the wait, nor is there data that needs protecting with a mutex. What should I do instead?

推荐答案

您在正确的轨道上...

You are on the right track...

只需添加一个布尔值(由互斥量保护,由条件变量表示),即可表示"go":

Just add a Boolean (protected by the mutex, indicated by the condition variable) that means "go":

std::mutex mutex;
std::condition_variable cv;
bool go = false;

std::thread thread1([&](){ std::unique_lock<std::mutex> lock(mutex); while (!go) cv.wait(lock);  std::cout << "GO1!\n"; });
std::thread thread2([&](){ std::unique_lock<std::mutex> lock(mutex); while (!go) cv.wait(lock);  std::cout << "GO2!\n"; });

{
    std::unique_lock<std::mutex> lock(mutex);
    go = true;
    cv.notify_all(); // Something happened - the threads can now process it
}

thread1.join();
thread2.join();

这篇关于使用condition_variable控制多线程流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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