原子锁是一条语句 临界区可以完成多条语句的锁定.
// CriticalSection.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "conio.h" #include "windows.h" CRITICAL_SECTION g_cs = { 0 }; LONG nValue = 0; void Print( ) { //进入临界区 - 加锁 EnterCriticalSection( &g_cs ); printf( "Long long long.......\n" ); nValue++; //离开临界区 - 解锁 LeaveCriticalSection( &g_cs ); } DWORD WINAPI PrintProc( LPVOID pParam ) { while( 1 ) { Print( ); Sleep( 100 ); } return 0; } void Create( ) { DWORD nThreadID = 0; HANDLE hThread[2] = { 0 }; hThread[0] = CreateThread( NULL, 0, PrintProc, NULL, 0, &nThreadID ); hThread[1] = CreateThread( NULL, 0, PrintProc, NULL, 0, &nThreadID ); getch( ); } int main(int argc, char* argv[]) { //初始化临界区 InitializeCriticalSection( &g_cs ); Create( ); //删除临界区 DeleteCriticalSection( &g_cs ); return 0; }