简体   繁体   中英

How to synchronize threads at regular intervals?

I have problems synchronizing several threads at regular intervals without consuming too much cpu while waiting.

I have a main thread, and several calculations threads that are all in the form:

CalcThread()   // x N threads
{
  loop{
    - do some calc stuff (variable but finite duration).
    - wait until main thread give a "continue" signal.
  }
}

MainThread()
{
  loop{
    - wait for all calc threads to be in waiting state.
    - do some calc synthesis stuff.
    - send a "continue" signal to calc threads.
  }
}

For the moment I make my threads waiting for each others looping the std::this_thread::yield() instruction with some condition on atomic shared flags. It works, BUT these loops are very CPU consuming.

There must be another solution, probably using mutex and condition_variable, but I am new to this, and all my attempt leads to failure...

Does anyone have an idea? Thanks for your help.

A condition variable is exactly what you want. Have your calc threads use std::condition_variable::wait to have them block until woken up by your main thread. Have the main thread call std::condition_variable::notify_all to unblock all of the calc threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM