[C++][Win32]临界区编程实例时间:2021-01-15 05:31:49#include <stdio.h> #include <certexit.h> CRITICAL_SECTION cs; int critical_value = 0; DWORD WINAPI ThreadProc(void *arg) { for (int i = 0; i < 5; ++i) { EnterCriticalSection(&cs); critical_value++; printf("critical_value = %d, i = %d/n", critical_value, i); LeaveCriticalSection(&cs); } return 1; } int main(int argc, char *argv[]) { HANDLE hThread1; HANDLE hThread2; // UINT uThreadID; InitializeCriticalSection(&cs); while (1) { hThread1 = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL); hThread2 = CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL); if (critical_value >= 15) { break; } } CloseHandle(hThread1); CloseHandle(hThread2); DeleteCriticalSection(&cs); return 0; }