用户模式下的多线程同步——关键段

关键段使线程访问共享资源之前独占它,共享资源访问结束后线程释放对资源的独占。但是这个过程中,系统也可能暂停该线程取调度其他线程,但是,在关键段释放之前,不会调度其他想访问同一资源的线程。

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

using namespace std;

int g_x = 0;
//把CRITICAL_SECTION定义成全局变量,以使所有的线程都能方便快速访问
CRITICAL_SECTION g_cs;

UINT WINAPI ThreadFunc1(PVOID pArguments)
{
    // EnterCriticalSection和LeaveCriticalSection把共享资源包起来
    EnterCriticalSection(&g_cs);
    cout << "ThreadFunc1.." << endl;
    int n = 0;
    while (n < 3)
    {
        g_x += n;
        n++;
    }
    LeaveCriticalSection(&g_cs);
    _endthreadex(0);
    return 0;
}
UINT WINAPI ThreadFunc2(PVOID pArguments)
{
    EnterCriticalSection(&g_cs);
    cout << "ThreadFunc2.." << endl;
    int n = 0;
    while (n < 5)
    {
        g_x += n;
        n++;
    }
    LeaveCriticalSection(&g_cs);
    _endthreadex(0);
    return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
    HANDLE   handle1, handle2;
    unsigned  unThread1ID, unThread2ID;

    cout << "g_x initial value: " << g_x << endl;
   //必须初始化CRITICAL_SECTION成员
   InitializeCriticalSection(&g_cs);
    handle1 = (HANDLE)_beginthreadex(NULL,
        0,
        &ThreadFunc1,
        NULL,
        0,
        &unThread1ID);
    handle2 = (HANDLE)_beginthreadex(NULL,
        0,
        &ThreadFunc2,
        NULL,
        0,
        &unThread2ID);
    WaitForSingleObject(handle1, INFINITE);
    WaitForSingleObject(handle2, INFINITE);
    cout << "g_x Final value: " << g_x << endl;
    //清理CRITICAL_SECTION成员
    DeleteCriticalSection(&g_cs);
    getchar();
    return 0;
}

有点: 容易使用,并且内部使用了Interlocked函数,因此执行速度非常快。
缺点: 不能在多个进程之间对线程同步

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值