[英]How to synchronize threads at regular intervals?
I have problems synchronizing several threads at regular intervals without consuming too much cpu while waiting.我在定期同步多个线程时遇到问题,而在等待时不会消耗太多 CPU。
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.目前,我让我的线程等待彼此循环 std::this_thread::yield() 指令,并在原子共享标志上有一些条件。 It works, BUT these loops are very CPU consuming.
它可以工作,但是这些循环非常消耗 CPU。
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.让您的计算线程使用
std::condition_variable::wait
让它们阻塞直到被主线程唤醒。 Have the main thread call std::condition_variable::notify_all
to unblock all of the calc threads.让主线程调用
std::condition_variable::notify_all
来解除对所有计算线程的阻塞。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.