線程需要在下面兩種情況下互相進行通訊:
•當有多個線程訪問共用資源而不使資源被破壞時。
•當一個線程需要將某個任務已經完成的情況通知另外一個或多個線程時。
所謂原子訪問,是指線程在訪問資源時能夠確保所有其他線程都不在同一時間內訪問相同的資源。
以InterLocked開始的函數都是戶數函數。使用互鎖函數的優點是:他的速度要比其他的CriticalSection,Mutex,Event,Semaphore快很多。調用一個互鎖函數通常會導致執行幾個CPU周期(通常小於50),並且不會從使用者方式轉換為核心方式(通常這需要執行1000個CPU周期)。可以查看msdn(http://msdn2.microsoft.com/en-us/library/ms686360.aspx)
第一個函數:
LONG InterlockedExchangeAdd(
PLONG plAddend,
LONG Increment);
一個簡單的例子:
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <process.h>
using namespace std;
#define THREAD_MAX 2 //不能超過64個核心對象
long g_x = 0;
unsigned __stdcall ThreadEntity(void * pVoid)
{
//g_x++; //沒有安全保護
InterlockedExchangeAdd(&g_x,1); //互鎖函數 有安全保護。
return 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hth[THREAD_MAX];
unsigned uiThreadID[THREAD_MAX];
cout << "start create children threadings:"<< endl;
for (inti=0; i<THREAD_MAX; ++i)
{
hth[i] = (HANDLE)_beginthreadex(NULL, // security
0, // stacksize
ThreadEntity,
(void*)&i, // arg list
0,
&uiThreadID[i]);
if (hth[i] == 0)
{
cout<< "Failed to create thread"<< endl;
}
}
WaitForMultipleObjects( THREAD_MAX, hth,true,100000);
for (inti=0; i<THREAD_MAX; ++i)
{
CloseHandle(hth[i]);
}
cout << "last: g_x is " << g_x << endl;
cout << "Primary thread terminating." << endl;
system("pause");
return 0;
}
第二個函數:
使用LONGInterlockedExchange(PLONG plTarget,LONG lValue);實現迴圈鎖:
// Global variableindicating whether a shared resource is in use or not
BOOL g_fResourceInUse =FALSE;
void Func1()
{
//Wait to access the resource.
while(InterlockedExchange(&g_fResourceInUse, TRUE) == TRUE)
Sleep(0);
//Access the resource.
//We no longer need to access the resource.
InterlockedExchange(&g_fResourceInUse,FALSE);
}
FangSH 15:19 2011-1-5