|
Boost : |
From: Sohail Somani (s.somani_at_[hidden])
Date: 2007-01-12 13:39:28
Hi,
Somewhat longer-than-normal-noise follows :)
Consider the following pseudo-code which has a race condition:
condition g_some_cond;
mutex g_condition_mtx;
void thread_fn()
{
{
... // get lock
g_some_cond.wait(condition_lock);
}
// do work
}
void main_thread()
{
thread_group grp;
// Start all threads and have them wait on the condition
for(i in [0,N)) grp.create_thread(&thread_fn);
{
... // get lock
g_some_cond.notify_all(); // let threads continue
}
}
The race condition is of course that it is possible that not all threads
actually start waiting on the condition before notify_all() is called.
In this case, it is possible to solve the race condition in two ways:
1) Have the last thread that reaches the condition wait, signal to the
main thread
2) Have the main thread checking the condition before notify_all()
I don't really like the first case because it requires bi-directional
signalling between the threads. Though in my ignorance, I really do
consider it the correct solution. The second solution would look
something like this:
while(true)
{
scoped_lock cond_lock(g_condition_mtx);
// .num_waiting_threads() is made up
if(N_EXPECTED_THREADS==g_some_cond.num_waiting_threads()){break;}
// release lock
}
Should the second pattern be encapsulated in the condition object
somehow? It is almost like timed_wait(mtx,xt,pred) but there is no
timeout. So maybe untimed_wait()? Is there another way to do this?
Thanks for your eyes!
Sohail
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk