windows下线程同步的方式(临界区)

临界区:
临界区是为了确保同一个代码片段在同一时间只能被一个线程访问,与原子锁不同的是临界区是多条指令的锁定,而原子锁仅仅对单条操作指令有效;临界区和原子锁只能控制同一个进程中线程的同步;

// CriticalSection.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "conio.h"
#include "windows.h"
CRITICAL_SECTION g_cs = { 0 };
int g_nValue = 0;
void Print( )
{   //进入临界区 - 加锁
    EnterCriticalSection( &g_cs );
    printf( "what  ...... what.........\n" );
    g_nValue++;
    //离开临界区 - 解锁
    LeaveCriticalSection( &g_cs );
}
DWORD WINAPI PrintProc( LPVOID pParam )
{
    while( 1 )
    {
        Print( );
        Sleep( 1000 );
    }
    return 0;
}
void Critical( )
{
    //初始化临界区
    InitializeCriticalSection( &g_cs );
    DWORD nThreadID = 0;
    HANDLE hThread[2] = { 0 };
    //创建线程
    hThread[0] = CreateThread( NULL, 0, PrintProc, NULL, 0, &nThreadID );
    hThread[1] = CreateThread( NULL, 0, PrintProc, NULL, 0, &nThreadID );
    //等候线程结束
    WaitForMultipleObjects( 2, hThread, TRUE, INFINITE );
    CloseHandle( hThread[0] );
    CloseHandle( hThread[1] );
    //删除临界区
    DeleteCriticalSection( &g_cs );
}
int main(int argc, char* argv[])
{
    Critical( );
 getch();
 return 0;
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值