大家说说,if...else能投替代condition啊
以下问题都是在成员函数send进行讨论的:
1. boost::condition 如何用if...else等 条件判断语句进行判断呢?
2. lock lk 感觉像一个辅助类,过了作用域,析构函数里面自动解锁。
send、receive函数 里的lk,都是放在 函数体开始,解锁肯定是函数末尾才解锁。
疑问是:(send操作) 资源被锁住了,还调用 buffer_not_full.wait(lk)? ,等待另外一个 receive操作,
能等待到吗,不是锁住了嘛,永远等待不了吧。
3.
buffer_not_full这个成员,没有看到初始化或者赋值。就可以这么使用之,不懂。
send函数里有一句:
buffer_not_empty.notify_one();
通知谁??? 为什么可以做到通知的就是 buffer_not_full???
class bounded_buffer : private boost::noncopyable{public: typedef boost::mutex::scoped_lock lock; bounded_buffer(int n) : begin(0), end(0), buffered(0), circular_buf(n) { } void send (int m) { // 加入消息 lock lk(monitor); while (buffered == circular_buf.size()) buffer_not_full.wait(lk); circular_buf[end] = m; end = (end+1) % circular_buf.size(); ++buffered; buffer_not_empty.notify_one(); } int receive() { // 取走消息 lock lk(monitor); while (buffered == 0) buffer_not_empty.wait(lk); int i = circular_buf[begin]; begin = (begin+1) % circular_buf.size(); --buffered; buffer_not_full.notify_one(); return i; }private: int begin, end, buffered; std::vector<int> circular_buf; boost::condition buffer_not_full, buffer_not_empty; boost::mutex monitor;};