[英]How to multi-thread this?
我希望有兩個主題。 第一個線程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和線程2都盡可能保持繁忙。 我想避免一個線程中的通知與另一個線程中的檢測之間的長時間延遲。 我嘗試使用pthread條件變量,但發現線程2執行“通知線程1我很忙”與thear2IsExclusive()上的waitForThread2()中的循環之間的延遲可能接近一秒鍾。 然后,我嘗試使用一個易失性sig_atomic_t共享變量來控制該變量,但是出了點問題,因此我不能正確地做它。
似乎您應該使用信號量來發信號,而不是使用“ while”循環來使線程空閑,等待某種情況發生。 空閑循環是不好的。
不要讓線程互相告訴我“我很忙”或“我不忙”,而應該考慮線程正在操作的數據對象。
如果兩個線程可能同時嘗試更改某些數據(例如,計數器),則意味着在那里需要一個互斥鎖。
當一個線程更改了其他線程可能正在等待的共享數據狀態時,請發出條件變量通知它們。 (例如,如果生產者線程將數據添加到隊列中,則它可能會發出“ dataAvailable”條件的信號,消費者可能正在等待該條件。)
在我看來,您似乎正在嘗試一個集合點(來自Ada的一個術語)。
第二個線程正在坐着,等待第一個線程調用它,然后在第一個線程等待時立即執行一些工作,在第一個線程完成后進行更多工作。
第一個線程正在“調用”第二個線程-如果第二個線程無法接聽電話,則會立即超時。
Ada直接以該語言支持該功能,但是假設不可以移植到Ada ...
這可以通過三個信號量來實現。 信號量1表示線程1已准備好集合。 信號量2表示線程2已准備好顛倒。 信號量3表示會合已完成。
線程1:獲得信號量1的默認值。
if Semaphore 2.acquire(timeout = 0) is successful # Thread 2 is ready
Semaphore 1.release() # Indicate I am ready
Semaphore 3.acquire() # Wait until the rendevous is complete.
Semaphore 3.release()
Semaphore 1.acquire() # Indicate I am not ready
Semaphore 2.release() # I am no longer using thread 2.
Do concurrent work
線程2:獲得信號量2的默認值。
Loop forever
Semaphore 3.acquire() # Indicate Rendevous is not complete.
Semaphore_2.release() # Indicate I am ready
Semaphore_1.acquire() # Wait for Thread 1 to be ready
Joint processing
Semaphore 1.release() # I am no longer using thread 1.
Semaphore 3.release() # Rendevous is complete.
Semaphore 2.acquire() # I am not ready
Post-processing
注意:從頭開始編寫,未經測試。 看起來比起初我想的要復雜得多; 我錯過了什么嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.