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;
}