Eugene Krel
sunmulA
- Joined
- 3/3/08
- Messages
- 399
- Points
- 28
I am working on a piece of code and part of it is a producer-consumer queue.
The following is my pop method:
The push method notifies.
The calling object destructor calls thread.join() to stop the thread.
The issue is that if the queue is empty it will just sit there waiting for the conditional variable to un-block and won't call the queue's destructor.
Stack trace:
What is the proper way to deal with that?
The naive solution is to create a pop() method that returns immediately if the queue is empty, but that is not multi-producer/consumer safe.
I am not sure that timed_join() is appropriate either since I can't predict how long it would take for the thread to complete if it's actually doing work.
The following is my pop method:
C++:
void pop(Data& popped_value)
{
boost::mutex::scoped_lock lock(m_mutex);
while (m_queue.empty()) //block while queue is empty
{
m_condition_var.wait(lock);
}
popped_value = m_queue.front();
//pop after copying the value to take exceptions into account
m_queue.pop();
}
The push method notifies.
The calling object destructor calls thread.join() to stop the thread.
The issue is that if the queue is empty it will just sit there waiting for the conditional variable to un-block and won't call the queue's destructor.
Stack trace:
C++:
thread 1:
pthread_cond_wait
boost::thread::join()
foo::~foo()
thread2:
pthread_cond_wait
foo::do_stuff_with_queue()
What is the proper way to deal with that?
The naive solution is to create a pop() method that returns immediately if the queue is empty, but that is not multi-producer/consumer safe.
I am not sure that timed_join() is appropriate either since I can't predict how long it would take for the thread to complete if it's actually doing work.