以前从第一章看到第七章,没注意做笔记,如今拾起,已忘得差不多了,所以趁暑假时间充裕,决心做好笔记,以备同志们和我自己学习查阅.
因此,本学习笔记从第八章开始写起......
(一) 用户模式下的线程同步
同步方法一: Interlocked系列函数
同步方法二: 应避免的方法
volatile BOOL g_fFinishedCalculation = FALSE;
int WINAPI _tWinMain(...) {
CreateThread(..., RecalcFunc, ...);
...
// Wait for the recalculation to complete.
while (!g_fFinishedCalculation)
;
...
}
DWORD WINAPI RecalcFunc(PVOID pvParam) {
// Perform the recalculation.
... g_fFinishedCalculation = TRUE;
return 0;
}
注意BOOL g_fFinishedCalculation的值必须是:volatile,以防止编译器优化.
同步方法三:
const int COUNT = 10;
int g_nSum = 0;
CRITICAL_SECTION g_cs;
DWORD WINAPI FirstThread(PVOID pvParam) {
EnterCriticalSection(&g_cs);
g_nSum = 0;
for (int n = 1; n <= COUNT; n++) {
g_nSum += n;
}
LeaveCriticalSection(&g_cs);
return(g_nSum);
}
DWORD WINAPI SecondThread(PVOID pvParam) {
EnterCriticalSection(&g_cs);
g_nSum = 0;
for (int n = 1; n <= COUNT; n++) {
g_nSum += n;
}
LeaveCriticalSection(&g_cs);
return(g_nSum);
}
1. 速度快,但是无法再多个进程之间对线程进行同步.
2. 注意还有一个函数TryEnterCriticalSection()
3. To use a spinlock with a critical section,
you should initialize the critical section by calling this function:
BOOL InitializeCriticalSectionAndSpinCount(
PCRITICAL_SECTION pcs,
DWORD dwSpinCount);
同步方法四: Slim读写锁
写:
VOID AcquireSRWLockExclusive(PSRWLOCK SRWLock);
VOID ReleaseSRWLockExclusive(PSRWLOCK SRWLock);
读:
VOID AcquireSRWLockShared(PSRWLOCK SRWLock);
VOID ReleaseSRWLockShared(PSRWLOCK SRWLock);