C++线程同步之临界区
#include <iostream> #include <windows.h> using namespace std; CRITICAL_SECTION cs; // LockCount 它被初始化为数值 -1,此数值等于或大于 0 时,表示此临界区被占用;等待获得临界区的线程数:LockCount - (RecursionCount -1) // RecursionCount 此字段包含所有者线程已经获得该临界区的次数 // OwningThread 此字段包含当前占用此临界区的线程的线程标识符,此线程 ID 与GetCurrentThreadId 所返回的 ID 相同 DWORD WINAPI ThreadProc1(LPVOID lpParameter) { for (int x = 0; x < 1000; x++) { EnterCriticalSection(&cs); Sleep(1000); printf("11111:%x %x %x\n", cs.LockCount, cs.RecursionCount, cs.OwningThread); LeaveCriticalSection(&cs); } return 0; } DWORD WINAPI ThreadProc2(LPVOID lpParameter) { for (int x = 0; x < 1000; x++) { EnterCriticalSection(&cs); Sleep(1000); printf("22222:%x %x %x\n", cs.LockCount, cs.RecursionCount, cs.OwningThread); LeaveCriticalSection(&cs); } return 0; } DWORD WINAPI ThreadProc3(LPVOID lpParameter) { for (int x = 0; x < 1000; x++) { EnterCriticalSection(&cs); Sleep(1000); printf("33333:%x %x %x\n", cs.LockCount, cs.RecursionCount, cs.OwningThread); LeaveCriticalSection(&cs); } return 0; } DWORD WINAPI ThreadProc4(LPVOID lpParameter) { for (int x = 0; x < 1000; x++) { EnterCriticalSection(&cs); Sleep(1000); printf("44444:%x %x %x\n", cs.LockCount, cs.RecursionCount, cs.OwningThread); LeaveCriticalSection(&cs); } return 0; } int main() { // 初始化临界区 InitializeCriticalSection(&cs); // printf("%x %x %x", cs.LockCount, cs.RecursionCount, cs.OwningThread); // 创建一个新的线程 HANDLE hTread1 = CreateThread(0, 0, ThreadProc1, 0, 0, 0); // 创建一个新的线程 HANDLE hTread2 = CreateThread(0, 0, ThreadProc2, 0, 0, 0); // 创建一个新的线程 HANDLE hTread3 = CreateThread(0, 0, ThreadProc3, 0, 0, 0); // 创建一个新的线程 HANDLE hTread4 = CreateThread(0, 0, ThreadProc4, 0, 0, 0); // 如果不在其它的地方引用它就关闭句柄 ::CloseHandle(hTread1); ::CloseHandle(hTread2); ::CloseHandle(hTread3); ::CloseHandle(hTread4); // 销毁临界区 // DeleteCriticalSection(&cs); getchar(); return 0; }