多个条件变量互相调用函数

Multiple Condition variable calling each other function

我看到了教程 here 边界缓冲区示例。作为参考,我也把它粘贴在这里。

#include <boost/circular_buffer.hpp>
   #include <boost/thread/mutex.hpp>
   #include <boost/thread/condition.hpp>
   #include <boost/thread/thread.hpp>
   #include <boost/call_traits.hpp>
   #include <boost/progress.hpp>
   #include <boost/bind.hpp>

   template <class T>
   class bounded_buffer {
   public:

      typedef boost::circular_buffer<T> container_type;
      typedef typename container_type::size_type size_type;
      typedef typename container_type::value_type value_type;
      typedef typename boost::call_traits<value_type>::param_type param_type;

      explicit bounded_buffer(size_type capacity) : m_unread(0), m_container(capacity) {}

      void push_front(boost::call_traits<value_type>::param_type item) {
         // param_type represents the "best" way to pass a parameter of type value_type to a method

         boost::mutex::scoped_lock lock(m_mutex);
         m_not_full.wait(lock, boost::bind(&bounded_buffer<value_type>::is_not_full, this));
         m_container.push_front(item);
         ++m_unread;
         lock.unlock();
         m_not_empty.notify_one();
      }

      void pop_back(value_type* pItem) {
         boost::mutex::scoped_lock lock(m_mutex);
         m_not_empty.wait(lock, boost::bind(&bounded_buffer<value_type>::is_not_empty, this));
         *pItem = m_container[--m_unread];
         lock.unlock();
         m_not_full.notify_one();
      }

   private:
      bounded_buffer(const bounded_buffer&);              // Disabled copy constructor
      bounded_buffer& operator = (const bounded_buffer&); // Disabled assign operator

      bool is_not_empty() const { return m_unread > 0; }
      bool is_not_full() const { return m_unread < m_container.capacity(); }

      size_type m_unread;
      container_type m_container;
      boost::mutex m_mutex;
      boost::condition m_not_empty;
      boost::condition m_not_full;
   };

当我尝试压入第一个元素时(push_front)。 “push_front()”函数到达条件变量并等待直到收到通知,一旦收到通知,它将检查函数 "is_not_full()",然后继续。但是因为它是第一个试图被推送的元素,它永远不会收到通知,因为函数 "pop_back()" 不会完成执行,因为缓冲区是空的。

我想得对吗?我可以将元素推送到这段代码吗?

谢谢

When I try to push the first element(push_front). " push_front()" function reaches condition variable and and goes to wait until it receives a notification [...]

这是错误的。仔细阅读此 API 的 the documentation。你描述的是

的行为
template<typename L> void wait(L & lock);

这是 public 成员函数列表中的第 3 个。但是,代码中对 wait 的调用有 两个 个参数;你的代码调用

template<typename L, typename Pr> void wait(L & lock, Pr pred);

这是该列表中的第 4 位。此函数被记录为与

相同
while ( !pred() )
    wait(lock);  // <-- This is where the thread waits for a notification

即先检查predicate,只有判断为false才会线程等待,直到收到通知。只要空缓冲区未满,谓词最初就会为真,因此无需等待通知即可继续执行。 (但是,如果您要构造一个容量为零的缓冲区,那么在尝试将第一个元素推入缓冲区时看起来确实会挂起。)