I have a simple threading question – how should the following be synchronized?
I have main thread and a secondary thread that does something only once and something – more that once.
Basically:
Secondary thread:
{
Do_Something_Once();
while (not_important_condition) {
Do_Something_Inside_Loop();
}
}
I want to suspend my main thread unless Do_Something_Once action is done and right now I use a plain bool value is_something_once_done = false; to indicate if the action is finished.
Hence, the code of my main thread looks like this:
{
Launch_Secondary_Thread();
while (!is_something_once_done) {
boost::this_thread::sleep(milliseconds(25));
}
}
which obviously isn’t the best way to perform such kind of synchronization.
Any alternatives (better if boost::thread – powered)?
Thank you
This is a job for condition variables.
Check out the Condition Variables section of the boost docs – the example there is almost exactly what you’re doing.
Whatever you do, don’t do a busy-wait loop with sleep