同步主和从线程的最佳方法,而无需使用Spinlock C++

发布于 2025-02-01 23:34:56 字数 623 浏览 1 评论 0原文

我有一个从主线程中执行无限循环的从属线程,该线程仅在主线程中执行循环中的代码。例如,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文