多線程之CS(關鍵段)


#include <iostream>
#include <process.h>
#include <windows.h>

long g_count = 0;
long g_sum   = 0;
static const int g_s_Count = 10;
CRITICAL_SECTION g_csThreadParamer;
CRITICAL_SECTION g_csThreadCode;
HANDLE          g_threadEvent;

unsigned int WINAPI ThreadFunc(void *p) {
    int nThreadNum = *(int *)p;

    Sleep(50);
    EnterCriticalSection(&g_csThreadCode);
    g_count++;
    printf("線程編號: %d, 全局資源值為: %d\n", nThreadNum, g_count);
    LeaveCriticalSection(&g_csThreadCode);
    SetEvent(g_threadEvent);
    return 0;
}

int main(void) {
    std::cout << "Create the Thread" << std::endl;

    g_threadEvent = CreateEvent(   NULL,
                                FALSE,
                                FALSE,
                                NULL);
    InitializeCriticalSection(&g_csThreadCode);
    InitializeCriticalSection(&g_csThreadParamer);
    HANDLE threadHandle[g_s_Count];

    for(int i = 0; i < g_s_Count; ) {

        threadHandle[i] = (HANDLE)_beginthreadex(NULL,
                                            0,
                                            ThreadFunc,
                                            &i,
                                            0,
                                            NULL);

        ++i;
    }

    WaitForMultipleObjects(g_s_Count, threadHandle, true, INFINITE);

    for(int i = 0; i < g_s_Count; ++i) {
        CloseHandle(threadHandle[i]);
    }
    DeleteCriticalSection(&g_csThreadCode);
    DeleteCriticalSection(&g_csThreadParamer);
    std::cout << "Thread Ending" << std::endl; 

    return 0;
}

分4步:

1,初始化CS段。

2,EnterCS段。

3,離開CS段。//主線程調度其他等待的線程執行。很好的達到互斥,但是不能同步。

4.,刪除CS段。





注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com