I am new toboost::thread
and am making a producer-consumer with a Monitor
. This is how I've coded it so far:
//{ 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;
}
So far I've written the Producer
like this:
void MatrixProducer::produce(){
while(true){
boost::mutex::scoped_lock lock(_mutex);
RawMatrix* matrix = rawMatrix();
_monitor->deposit(matrix);
boost::this_thread::sleep(boost::posix_time::milliseconds(sleep_msecs));
}
}
boost::thread& MatrixProducer::start(){
_thread = boost::thread(boost::bind(&MatrixProducer::produce, this));
return _thread;
}
RawMatrix* MatrixProducer::rawMatrix(){/*Generates and returns a matrix*/}
The Consumer
:
boost::thread& MatrixConsumer::start(){
_thread = boost::thread(boost::bind(&MatrixConsumer::consume, this));
return _thread;
}
void MatrixConsumer::consume(){
while(true){
boost::mutex::scoped_lock lock(_mutex);
RawMatrix* matrix = _monitor->withdraw();
_matrix->deposit(Matrix);
boost::this_thread::sleep(boost::posix_time::milliseconds(sleep_msecs));
}
}
Is this okay? Also, who will have the ownership of this: Producer
or Consumer
and Monitor
?
ho
w to do something; first its off-topic but secondly there are fewer experts roaming around (and thus you may not get a good answer). So ask thehow
question on SO to get the best answers. \$\endgroup\$