我有一个问题,我的condition_variables似乎不能互相通知。也就是说,我下面的代码在等待和通知线程中都使用了互斥锁,但仍然不能正确运行。
我是不是漏掉了什么?
谢谢。
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
std::condition_variable cv_one;
std::condition_variable cv_two;
std::mutex m_one;
std::mutex m_two;
void one(  )
{
  std::unique_lock< std::mutex > lock { m_one };
  cv_one.notify_one( );
  std::cout << "one" << std::endl;
}
void two(  )
{
  {
    std::unique_lock< std::mutex > lock { m_one };
    cv_one.wait( lock );
    std::cout << "two" << std::endl;
  }
  {
    std::unique_lock< std::mutex > lock { m_two };
    cv_two.notify_one(  );
  }
}
void three( )
{
  std::unique_lock< std::mutex > lock { m_two };
  cv_two.wait( lock );
  std::cout << "three" << std::endl;
}
int main( int argc, char **argv )
{
  std::thread thread_one( one );
  std::thread thread_two( two );
  std::thread thread_three( three );
  std::cin.get(  );
  cv_one.notify_all( );
  thread_three.join( );
  thread_two.join( );
  thread_one.join( );
  return 0;
}发布于 2014-06-25 12:40:27
条件变量不会相互通知,因为您在错误的时间通知。例如,如果one在two调用cv_one.wait(lock)之前调用cv_one.notify(),那么two将永远阻塞。就two而言,在它等待的时候没有线程通知它。这就是@v.oddou的意思,通知标志不会被存储。
std::cin行起到了延迟的作用,这就是为什么这里的输出是正确的。所有的线程都会到达它们等待条件变量的地方,在你按下按钮的延迟时间内。
您可以在此代码示例中看到问题的发生,它显示了线程在被唤醒时开始等待的时间。我切换到单个字符,这样输出就不会乱七八糟。
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
std::condition_variable cv_one;
std::condition_variable cv_two;
std::mutex m_one;
std::mutex m_two;
void one()
{
    std::unique_lock< std::mutex > lock { m_one };
    std::cout << "x" << std::endl;
    cv_one.notify_one();
    std::cout << "a" << std::endl;
}
void two()
{
    {
        std::unique_lock< std::mutex > lock { m_one };
        std::cout << "y" << std::endl;
        cv_one.wait( lock );
        std::cout << "b" << std::endl;
    }
    {
        std::unique_lock< std::mutex > lock { m_two };
        cv_two.notify_one();
    }
}
void three()
{
    std::unique_lock< std::mutex > lock { m_two };
    std::cout << "z" << std::endl;
    cv_two.wait( lock );
    std::cout << "c" << std::endl;
}
int main( int argc, char **argv )
{
    std::thread thread_one(one);
    std::thread thread_two(two);
    std::thread thread_three(three);
    std::cout << "d" << std::endl;
    cv_one.notify_all();
    thread_three.join();
    thread_two.join();
    thread_one.join();
    return 0;
}https://stackoverflow.com/questions/24397545
复制相似问题