I'm trying to implement a producer-consumer pattern. I did my homework but still couldn't be sure about it. The implementation is as follows:
boost::mutex m_mutex;
boost::container::deque<T> m_buffer;
boost::condition_variable fifo_loaded;
T pop(void)
{
boost::mutex::scoped_lock lock(m_mutex);
while (m_buffer.empty())
{
fifo_loaded.wait(lock); // As i understand, it releases the mutex,
and whenever it is notified,
gets it back again
}
T tmp = m_buffer.front();
m_buffer.pop_front();
return tmp;
}
void push(const T &newElem)
{
boost::mutex::scoped_lock lock(m_mutex);
m_buffer.push_back(newElem);
lock.unlock();
fifo_loaded.notify_one();
}
And the producer-consumer pair is like below. Is it OK or do i need synchronization in here too ?
void produce_thread()
{
while(true)
{
double data = generate_data();
m_buffer.push(data);
}
}
void consume_thread()
{
while (true)
{
double data = m_buffer.pop();
process_data(data);
}
}
void start_system()
{
boost::thread* thread_a = new boost::thread(capture_thread);
boost::thread* thread_b = new boost::thread(process_thread);
}
And how can i stop the threads manually ? Is it OK to manage it with a bool like the one below ?
bool enabled;
void produce_thread()
{
while(enabled)
{
// Do stuff
}
}
void consume_thread()
{
while (enabled)
{
// Do stuff
}
}