// Critsetion.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include <process.h>
using namespace std;


CRITICAL_SECTION g_cs;
char name[]="zhangdongsheng";

unsigned __stdcall ThreadPoc1( void* pArguments)
{
while (1)
{
EnterCriticalSection(&g_cs); //如果此处不对全局变量name进行加锁
//那么输出结果将有可能出现不一致现象
memset(name,0,sizeof(name));
strcpy(name,"Thread1");
Sleep(600);
cout<<"Thread1 "<<name<<endl;
LeaveCriticalSection(&g_cs);
}

return 0;
}
unsigned __stdcall ThreadPoc2( void* pArguments)
{
while(1)
{
EnterCriticalSection(&g_cs);
memset(name,0,sizeof(name));
strcpy(name,"Thread2");
Sleep(500);
cout<<"Thread2 "<<name<<endl;
LeaveCriticalSection(&g_cs);
}

return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
InitializeCriticalSection(&g_cs);
HANDLE hThread1=(HANDLE)_beginthreadex(NULL,0,ThreadPoc1,NULL,0,NULL);
HANDLE hThread2=(HANDLE)_beginthreadex(NULL,0,ThreadPoc2,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
while(1)
{
Sleep(500);
}
DeleteCriticalSection(&g_cs);
return 0;
}


不加锁会出现不一致的情况

CRITICAL_SECTION 学习_c++

加锁后:

CRITICAL_SECTION 学习_加锁_02