我希望有两个线程。第一个 thread1 偶尔会调用以下伪函数:
void waitForThread2() {
if (thread2 is not idle) {
return;
}
notifyThread2IamReady(); // i.e. via 1st condition variable
Wait for thread2 to finish exclusive access. // i.e. via 2nd condition variable.
}
第二个 thread2 永远处于以下伪循环中:
for (;;) {
Notify thread1 I am idle.
Wait for thread1 to be ready. // i.e. via 1st condition variable.
Notify thread1 I am exclusive.
Do some work while thread1 is blocked.
Notify thread1 I am busy. // i.e. via 2nd condition variable.
Do some work in parallel with thread1.
}
编写此代码的最佳方法是什么,以使 thread1 和 thread2 在具有多核的机器上尽可能保持忙碌。我想避免一个线程的通知和另一个线程的检测之间的长时间延迟。我尝试使用 pthread 条件变量,但发现线程 2 执行“通知线程 1 我很忙”与 thear2IsExclusive() 上的 waitForThread2() 中的循环之间的延迟可能长达近一秒。然后我尝试使用 volatile sig_atomic_t 共享变量来控制它,但是出了点问题,所以我一定没有正确地做。