1共享變量的原子性加減(負值)互鎖函數InterlockedExchangeAdd。返回原值。
2原子性值值替換函數InterlockedExchange和InterlockedExchangePointer。兩個函數都返回原始值。利用共享變量進行互斥的例子:注意事項Winddows核心編程P175
// Global variable
BOOL g_fResoureInUse = FALSE;
void Func(){
while(InterlockedExchange(&g_fResoureInUse, TRUE)==TRUE) Sleep(0);
//...
// exit func
InterlockedExchange(&g_fResoureInUse, FALSE);
}
循環鎖極大可能浪費CPU時間。
3 InterlockedCompareExchange和InterlockedCompareExchangePointer該函數對當前值(plDestination參數指向的值)與lComparand參數中傳遞的值進行比較。如果兩個值相同,那麼*plDestination改爲lExchange參數的值。如果*plDestination中的值與lExchange的值不匹配,*plDestination保持不變。該函數返回*plDestination中的原始值。記住,所有這些操作都是作爲一個原子執行單位來進行的。
二 代碼片段線程同步
1 關鍵代碼段互斥
#include <iostream>
#include <Windows.h>
#include <process.h>
using namespace std;
const int MAX_TIMES = 100;
int g_index = 0;
DWORD g_dwTimes[MAX_TIMES];
CRITICAL_SECTION cs;
void threadFunc1(void *)
{
while(g_index < MAX_TIMES){
EnterCriticalSection(&cs);
g_dwTimes[g_index] = GetTickCount();
g_index++;
cout<<g_dwTimes[g_index-1]<<" "<<g_index-1<<endl;
LeaveCriticalSection(&cs);
}
}
void threadFunc2(void *)
{
while(g_index < MAX_TIMES){
EnterCriticalSection(&cs);
g_index++;
g_dwTimes[g_index-1] = GetTickCount();
cout<<g_dwTimes[g_index-1]<<" "<<g_index-1<<endl;
LeaveCriticalSection(&cs);
}
}
int main()
{
InitializeCriticalSection(&cs);
_beginthread(&threadFunc1, 0, 0);
_beginthread(&threadFunc2, 0, 0);
Sleep(INFINITE);
return 0;
}
三 使用事件內核對象進行線程同步
#include <iostream>
#include <Windows.h>
#include <process.h>
using namespace std;
HANDLE g_event;
UINT WINAPI threadFunc1(void *)
{
// 等待事件發送信號
WaitForSingleObject(g_event, INFINITE);
return 0;
}
UINT WINAPI threadFunc2(void *)
{
// 等待事件發送信號
WaitForSingleObject(g_event, INFINITE);
return 0;
}
UINT WINAPI threadFunc3(void *)
{
// 等待事件發送信號
WaitForSingleObject(g_event, INFINITE);
return 0;
}
int main()
{
/**
* 以下設置自動還原無信號狀態,初始狀態爲無信號
*/
g_event = CreateEvent(NULL, true, false, NULL);
UINT hThread[3];
UINT tid;
hThread[0] = _beginthreadex(0, 0, &threadFunc1, NULL, 0, &tid);
hThread[1] = _beginthreadex(0, 0, &threadFunc2, NULL, 0, &tid);
hThread[2] = _beginthreadex(0, 0, &threadFunc3, NULL, 0, &tid);
// write shared buffer
// ...
// 設置有信號狀態
SetEvent(g_event);
Sleep(1000);
return 0;
}
等待事件通知說明:摘自windows核心編程