一 共享变量的原子修改函数——互锁函数
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核心编程