views:

142

answers:

4
+1  A: 

Insert code that is appropriate for your platform where I have added comments below:

{
   // Create event visible by second thread to be signalled on completion
   Launch_Secondary_Thread();

   // Wait for event to be signalled
}

{
   Do_Something_Once();
   // set the event state to signalled so that 1st thread knows to continue working

   while (not_important_condition) {
      Do_Something_Inside_Loop();
   }
}

Make sure that the event DOES get signalled, even if 2nd thread exits abnormally after an exception or other error. If not, your 1st thread will never wake up. Unless you can put a timeout on the wait.

Steve Townsend
A: 

You're free to go with mutex locks!

Do_Something_Once()
{
   boost::mutex::scoped_lock(mutex);
   // ...
}

Update:

For your particular case I would go with condition variable, as others suggested.

Andrejs Cainikovs
Can you explain how this would work please?
Steve Townsend
Updated with boost specific example.
Andrejs Cainikovs
-1 for incomplete or incorrect answer
Steve Townsend
Trying to undo down vote after edit is not working - adding +1 elsewhere in your history
Steve Townsend
Heh, thanks anyway.
Andrejs Cainikovs
+4  A: 

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

David Gelhar
+1 for boost-specific solution as requested
Steve Townsend
"Whatever you do, don't do a busy-wait loop with sleep" - Care to elaborate why this is such bad thing?
StackedCrooked
David Gelhar
+2  A: 

You could consider using boost's condition variable mechanism. It is designed for this scenario.

Reed Copsey