C++ boost::线程生产者消费者
我是新来的C++ boost::线程生产者消费者,c++,boost,boost-thread,producer-consumer,C++,Boost,Boost Thread,Producer Consumer,我是新来的boost::thread。到目前为止,我就是这样编码的 //{ Declarations in header private: boost::condition_variable _condition; boost::mutex _mutex; std::deque<RawMatrix*> _queue; boost::detail::atomic_count _count; //} void Matr
boost::thread
。到目前为止,我就是这样编码的
//{ Declarations in header
private:
boost::condition_variable _condition;
boost::mutex _mutex;
std::deque<RawMatrix*> _queue;
boost::detail::atomic_count _count;
//}
void MatrixMonitor::deposit(RawMatrix* rawMatrix){
boost::unique_lock<boost::mutex> lock(_mutex);
_condition.wait(lock, boost::bind(std::less_equal<int>(), boost::ref(_count), max));
_queue.push_back(rawMatrix);
++_count;
_condition.notify_one();
}
RawMatrix* MatrixMonitor::withdraw(){
boost::unique_lock<boost::mutex> lock(_mutex);
_condition.wait(lock, boost::bind(std::greater_equal<int>(), boost::ref(_count), min));
RawMatrix* elem = _queue.front();
_queue.pop_front();
--_count;
_condition.notify_one();
return elem;
}
但是我应该如何在某个时间间隔内运行product()
。我不知道我需要在《消费者》杂志上写些什么。谁将拥有这个生产者、消费者和监测仪的所有权
可以吗
根据您的设计,生产者拥有队列,队列拥有消费者可能是有道理的。如果我在调用
rawMatrix()
之前解锁互斥体,我是否仍然需要锁定rawMatrix()
中的互斥体?当然,是rawMatrix()中的互斥体存在保护队列和计数不受其他线程看到它们处于不一致状态的影响。
void MatrixProducer::produce(){
boost::mutex::scoped_lock lock(_mutex);
RawMatrix* matrix = rawMatrix();
_monitor->deposit(matrix);
}
RawMatrix* MatrixProducer::rawMatrix(){/*Generates and returns a matrix*/}