2つのスレッドが必要です。最初の 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.
}
2 番目の 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.
}
複数のコアを持つマシンでスレッド 1 とスレッド 2 の両方が可能な限りビジー状態に保たれるようにこれを記述する最良の方法は何ですか。あるスレッドでの通知と別のスレッドによる検出との間の長い遅延を避けたいと思います。pthread 条件変数を使用してみましたが、thread2 が 'notify thread1 I am busy' を実行してから、ar2IsExclusive() の waitForThread2() のループまでの遅延が最大で 1 秒近くになることがわかりました。次に、揮発性の sig_atomic_t 共有変数を使用して同じものを制御しようとしましたが、何かがうまくいかないので、正しく実行していないに違いありません。