Yippie-Ki-Yay
Yippie-Ki-Yay

Reputation: 22794

C++ - basic thread question

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

Upvotes: 1

Views: 318

Answers (4)

Steve Townsend
Steve Townsend

Reputation: 54128

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.

Upvotes: 1

Andrejs Cainikovs
Andrejs Cainikovs

Reputation: 28424

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.

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564333

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

Upvotes: 2

David Gelhar
David Gelhar

Reputation: 27900

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

Upvotes: 4

Related Questions