I have an implementation of Producer-Consumer multi-threaded interaction.It It works.But, but I feel that during the execution wait states happen too often between Consumer
thread and Producer. In my case, Consumer
accesses a queue at random intervals and takes data from it. Now, the producer thread runs during the whole process life time. The producer thread works as caching machine. It checks in a loop if the size of queue is smaller than the maximum cache size allowed, and if that's the case, it keeps pushing new data into that cache.
My concern is that when the consumer tries to access the queue, the last is still locked by the producer thread and the consumer should wait. I would like to get a feedback if what I am doing is optimal in terms of interaction flow between producer and consumer.
Here is how I am doing it now:
//Called by consumer(main thead) to retrieve data from cache
uint8_t* Worker::GetFrame() {
boost::unique_lock<boost::mutex> lk(_frameCacheMutex);
//If the cache is empty:
while (0 == _frames_cache.size()) {
//tell Producer to push data into cache
_fill_cache_wait_cond.notify_one();
//wait for the data to arrive(will be signaled by worker thread)
_get_frame_wait_cond.wait(lk);
}
uint8_t * fr = _frames_cache.front();
_frames_cache.pop();
// notify worker thread to continue caching
_fill_cache_wait_cond.notify_one();
return fr;
}
Producer thread:
void Worker::operator () () {
//Some init here..
while (isRunning) {
boost::unique_lock<boost::mutex> lk(_frameCacheMutex);
/// Here create the data for cache...
_frames_cache.push(data);
/// Notify waiting main thread to take data
_get_frame_wait_cond.notify_one();
/// If the cache is full ,wait
while (_frames_cache.size() == cacheMaxSize ){
_fill_cache_wait_cond.wait(lk);
}
}
}