同步主和从线程的最佳方法,而无需使用Spinlock C++
我有一个从主线程中执行无限循环的从属线程,该线程仅在主线程中执行循环中的代码。例如,
void slaveFunc(){
for(;;){
//// Wait here for go signal from Master thread
doStuff(); // doStuff() may return instantly or take hours.
}
return;
}
主线程还可以运行一个循环,
void masterFunc(){
for(;;){
Instruct slaveThread to execute 1 iteration of the loop
Wait for slaveThread to complete 1 iteration of the loop
}
return;
}
目前我正在使用std :: mutex
,因此,当MasterThread释放Mutex时,从属线程将执行循环的迭代。同样,当从属线释放互斥X时,主线程可以指示从线程执行循环的另一个迭代。我不得不使用经常进行轮询的STD :: Atomic来确保当一个线程释放静音时,另一个线程将锁定。
是否有一种更优雅的方法可以做到这一点,而无需诉诸于旋转锁?
I've got a slave thread that executes a infinite loop, which only executes the code within the loop once on instruction from the master thread. eg
void slaveFunc(){
for(;;){
//// Wait here for go signal from Master thread
doStuff(); // doStuff() may return instantly or take hours.
}
return;
}
The master thread also runs a loop
void masterFunc(){
for(;;){
Instruct slaveThread to execute 1 iteration of the loop
Wait for slaveThread to complete 1 iteration of the loop
}
return;
}
Presently I'm using a std::mutex
, so when the masterThread releases the mutex the slave thread executes an iteration of the loop. Likewise, when the slave thread releases the mutex, the master thread can instruct the slave thread to execute another iteration of the loop. I've had to use a constantly polled std::atomic to ensure that when one thread releases the mutex, the other thread will lock it.
Is there a more graceful way of doing this, without resorting to a spinlock?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论