我對volatile
的使用情況有疑問。我通常會嘗試跨線程共享的所有變量都具有volatile
關鍵字,以確保直接訪問內存,並且當然通過互斥鎖保護。多線程應用程序中的易失性C/C++
但是,如果共享變量以確保一致性,真的需要volatile
嗎?
我個例子來說:
Thread1: //(affects it behaviour with the variable)
mymutex.lock();
if(variable)
{
...
variable = false;
}
mymutex.unlock();
Thread2:
mymutex.lock();
variable = true;
mymutex.unlock();
在上例,僅thread2
寫入和thread1
讀/寫。是否有可能緩存variable
並且線程不讀取新值?即使互斥體設置正確?在這種情況下,我需要volatile
嗎?
我在問這個,因爲不是變量,我有一個std::vector
,它不能變化。如果沒有volatile
關鍵字,我不能100%確定這種方法是安全的。
謝謝。
編輯:適當重新構造問題。
只要你的變量訪問由互斥保護 - [你沒有使用'volatile']( http://stackoverflow.com/questions/11172922/does-stdmutex-create-a-fence) –
所以,如果我得到您的評論。那麼在鎖釋放後,所有在互斥體/信號量/ CriticalSection中訪問的變量都會刷新並可見於其他線程? – DarkZeros
@DarkZeros正好!這就是它的工作原理。 –