VC 下保證原子性的操作
這裏臨界區控制結構體操作都是基於這個結構體的
typedef struct CRITICAL_SECTION {
unsigned int LockCount; /* Nesting count on critical section */
HANDLE OwnerThread; /* Handle of owner thread */
HANDLE hCrit; /* Handle to this critical section */
DWORD needtrap; /* Trap in when freeing critical section */
DWORD dwContentions; /* Count of contentions */
} CRITICAL_SECTION, *LPCRITICAL_SECTION;
void InitializeCriticalSection(LPCRITICAL_SECTION lpCriticalSection );//初始化
void WINAPI EnterCriticalSection(__inout LPCRITICAL_SECTION lpCriticalSection);//上鎖
void WINAPI LeaveCriticalSection( _Inout_LPCRITICAL_SECTION lpCriticalSection);//解鎖
void WINAPI DeleteCriticalSection(_Inout_ LPCRITICAL_SECTION lpCriticalSection);//釋放臨界區內存
上鎖以後就會讓其他線程在訪問到臨界區變量(全局變量)的時候進行等待
直到解鎖以後才能使用。
#include <stdio.h>
#include <windows.h>
HANDLE hThread_1;
HANDLE hThread_2;
HANDLE hThread_3;
int n;
class StaticLock
{
public:
StaticLock()
{
InitializeCriticalSection(&g_csTerm);
};
~StaticLock()
{
DeleteCriticalSection(&g_csTerm);
};
void lockon()
{
EnterCriticalSection(&g_csTerm);
};
void lockoff()
{
LeaveCriticalSection(&g_csTerm);
};
private:
CRITICAL_SECTION g_csTerm;
};
StaticLock lock;
DWORD WINAPI fun(LPVOID)
{
while(1)
{
lock.lockon();
if(n>50)
{
break;
}
else
{
++n;
printf("%d\n",n);
}
lock.lockoff();
}
lock.lockoff();
}
int main(void)
{
n = 0;
hThread_1 = CreateThread(NULL,0,fun,NULL,0,NULL);
hThread_1 = CreateThread(NULL,0,fun,NULL,0,NULL);
hThread_1 = CreateThread(NULL,0,fun,NULL,0,NULL);
WaitForSingleObject(hThread_1, INFINITE);
WaitForSingleObject(hThread_2, INFINITE);
WaitForSingleObject(hThread_3, INFINITE);
CloseHandle(hThread_1);
CloseHandle(hThread_2);
CloseHandle(hThread_3);
return 0;
}