简体   繁体   English

C ++中的condition_variable等待

[英]condition_variable wait in C++

I have been trying condition_variable::wait and precisely I am using : 我一直在尝试condition_variable :: wait并且正好在使用:

 template< class Predicate >
 void wait( std::unique_lock<std::mutex>& lock, Predicate pred );

but I am a little bit confused when I executed it. 但是当我执行它时我有点困惑。 This the simple example: 这个简单的例子:

 std::condition_variable cv;
 std::mutex cv_m;
 bool flag = false;

 void waits()
 {
   std::unique_lock<std::mutex> lk(cv_m);
   std::cerr << "Waiting... \n";

   cv.wait(lk,[]() {return flag == true;});
   std::cerr << "...finished waiting " << flag << std::endl;
 }

 void signals()
 {
    //std::this_thread::sleep_for(std::chrono::seconds(1));

   std::unique_lock<std::mutex> lk(cv_m);
   std::cout <<"Counting...."<< std::endl;
   flag = true;
     for(int i = 0; i < 5; i++) {
       std::cout << i << std::endl;
   }

  cv.notify_all();

 }

 int main()
 {
   std::thread t1(waits), t2(waits), t3(waits), t4(signals);
   t1.join();
   t2.join();
   t3.join();
   t4.join();

   return 0;
 }

if I am delay the signals() with 如果我延迟signal()与

  std::this_thread::sleep_for(std::chrono::seconds(1));

it works as expected while if I put the above line under comment the output it is a mess. 它按预期工作,而如果我将上面的行放在注释下,则输出混乱。 Shouldnd the wait condition put on hold the execution of waits() anyway ? 无论如何,等待条件是否应该搁置waits()的执行? Why do I need a delay the output changes every time and most of the time messed up ? 为什么我需要延迟输出每次都更改,而大多数时候却搞砸了?

An example of the output 输出示例

 Waiting... 
 Counting....
 0
 1
 2
 3
 4
 Waiting... 
 ...finished waiting 1
 Waiting... 
 ...finished waiting 1
 ...finished waiting 1

Thank you for any help 感谢您的任何帮助

You have a race condition. 您有比赛条件。 It is possible for t4 to grab the mutex and run to completion before the other threads have a chance to get into the wait. t4有可能在其他线程有机会进入等待之前抓住互斥锁并运行完成。 Thus they miss the signal. 因此他们错过了信号。

You need to synchronize so that the t1 , t2 , and t3 get into the wait before t4 starts. 您需要进行同步,以便t1t2t3t4开始之前进入等待状态。 Anytime a sleep seems to fix a problem in threaded code, you probably have a race condition that requires real synchronization to fix properly. 每当睡眠似乎可以解决线程代码中的问题时,您就可能遇到竞争状况,需要真正的同步才能正确解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM