【发布时间】:2020-02-15 15:15:26
【问题描述】:
我遇到了教程here Bounding Buffer 示例。作为参考,我也将其粘贴在这里。
#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()”不会完成执行,因为缓冲区是空的。
我的想法正确吗?我可以将元素推送到这段代码吗?
谢谢
【问题讨论】:
-
你阅读过 boost::condition 的文档吗?因为这不是我手动编写条件等待循环的方式,也不是谓词在
std::condition_variable中的行为方式... -
@Useless 正确阅读问题。该代码来自 Boost 文档。
-
OP 声称它会在调用
is_not_full之前等待通知。我在问这是否真的是它的行为方式,因为标准 condvar 循环是while(!pred) wait(),也就是说,我希望在等待可能永远不会出现的信号之前调用is_not_full。
标签: c++ boost message-queue condition-variable