第八章 用戶模式下線程同步
以下線程同步方法僅限于同一進程內(nèi)的不同線程。不適用于不同進程的不線程。
1.原子訪問 Atomic Access
InterlockedExchange系列函數(shù)是針對于某個單一變量進行的原子操作
Volatile關(guān)鍵字告訴編譯器不要對變量的訪問做任何優(yōu)化,每次讀訪變量的值都要去內(nèi)存中讀而不是在寄存器中讀。
2.臨界區(qū) 使一組操作原子化。
臨界區(qū)對象用法:InitializeCriticalSection、(TryEnterCriticalSection ),EnterCriticalSection、LeaveCriticalSection、DeleteCriticalSection
EnterCriticalSection
線程進入臨界區(qū)后 若其它線程試圖想進入該臨界區(qū)線程會處于阻塞(Wait)狀態(tài),使它們不占用任何CPU.
3.讀寫鎖
允許多個讀線程同時讀取共享數(shù)據(jù),但在同一時間只允許一個寫線程修改共享數(shù)據(jù)。
用法:
InitializeSRWLock
寫者:
AcquireSRWLockExclusive、ReleaseSRWLockExclusive
讀者:
AcquireSRWLockShared、ReleaseSRWLockShared
我們并不需要銷毀讀寫鎖對象,因為系統(tǒng)自動處理讀寫鎖對象。
讀寫鎖的效率比臨界區(qū)要高到少一倍左右。
4.效率
To summarize, if you want to get the best performance in an application,
you should try to use nonshared data first and then use volatile reads, volatile writes, interlocked APIs, SRWLocks, critical sections.
And if all of these won't work for your situation, then and only then, use kernel objects
5.條件變量
條件變量要與臨界區(qū)對象或讀寫鎖對象一起使用。
SleepConditionVariableCS、SleepConditionVariableSRW
WakeConditionVariable、WakeAllConditionVariable
6.Common API
InterlockedExchangeAdd InterlockedExchangeAdd64
InterlockedExchange InterlockedExchangePointer
InterlockedBitTestAndReset