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;
}
相關文章
相關標籤/搜索