多线程之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段。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值