我希望有兩個線程。第一個線程1偶爾會調用下面的僞功能:如何多線程呢?
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是永遠在下面的僞循環:
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和線程是最好的方式在有多個內核的機器上儘可能地保持忙碌。我想避免在一個線程中的通知和另一個線程的檢測之間的長時間延遲。我試過使用pthread條件變量,但發現thread2正在執行'notify thread1 I busy'和while()onS2IsExclusive()中的waitForThread2()循環之間的延遲可能高達幾乎一秒的延遲。然後我嘗試使用一個易變的sig_atomic_t共享變量來控制它,但是出了問題,所以我不能正確地做到這一點。
你會過得更好告訴人們,你實際上是試圖解決,而不是要求他們執行你已經設想了一個解決問題的... – 2010-05-25 02:13:47
僞代碼並沒有太大的意義。你如何通知另一個線程你忙?爲什麼?此外,你在這裏關注線程;通常,您需要同步數據。你同步哪些數據,以及你的並行操作如何? – WhirlWind 2010-05-25 02:16:45
如果你的condvars正在採取任何行動,你正在做的事情非常錯誤。此外,要做的規範是鎖定數據結構,而不是「通知其他線程」;後者不會縮放。 – 2010-05-25 02:28:53