WIN32临界区线程锁EnterCriticalSection和LeaveCriticalSection

//创建全局变量结构体
CRITICAL_SECTION cs;

//初始化变量结构体
InitializeCriticalSection(&cs);    

//循环之前判断是否拿到令牌
EnterCriticalSection(&cs);    

//代码区

//释放令牌
LeaveCriticalSection(&cs);

 

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

using namespace std;
//创建全局变量结构体
CRITICAL_SECTION cs;
int i = 10;
DWORD WINAPI ThreadProc(LPVOID lpParamter)
{
    while(Sleep(1000),EnterCriticalSection(&cs) ,i>0)
    {
        //EnterCriticalSection(&cs);
        printf("ThreadProc %d 还有 %d 张票\n",lpParamter,i);
        Sleep(500);
        i--;
        printf("ThreadProc %d 卖出 1 张票还剩%d 张票\n",lpParamter,i);
        LeaveCriticalSection(&cs);
    }
    return 0;
}

DWORD WINAPI ThreadProc1(LPVOID lpParamter)
{
    //循环之前判断是否拿到令牌
    while(Sleep(1000),EnterCriticalSection(&cs),i>0)
    {
        printf("ThreadProc1还有 %d 张票\n",i);
        //Sleep(2000);
        i--;
        printf("ThreadProc1卖出 1 张票还剩%d 张票\n",i);
        //释放令牌
        LeaveCriticalSection(&cs);
    }
    return 0;
}

DWORD WINAPI ThreadProc2(LPVOID lpParamter)
{
    while(Sleep(500),EnterCriticalSection(&cs),i>0)
    {
        printf("ThreadProc2还有 %d 张票\n",i);
        //Sleep(1000);
        i--;
        printf("ThreadProc2卖出 1 张票还剩%d 张票\n",i);
        LeaveCriticalSection(&cs);
    }
    return 5;
}

int main()
{
    
    DWORD ThreadId1 = 0;
    DWORD ThreadId2 = 0;
    HANDLE hThread[2];
    DWORD dwr1;
    DWORD dwr2;
    int p1 = 1;
    int p2 = 2;
    //初始化变量结构体
    InitializeCriticalSection(&cs);    
    
    hThread[0] = CreateThread(NULL, 0, ThreadProc1, (LPVOID)p1, 0, &ThreadId1);
    hThread[1] = CreateThread(NULL, 0, ThreadProc2, (LPVOID)p2, 0, &ThreadId2);
    
    WaitForMultipleObjects(2,hThread,TRUE,INFINITE);

    CloseHandle(hThread[0]);
    CloseHandle(hThread[1]);
    
    system("pause");
    return 0;
}

 

posted @ 2020-06-16 16:52  温暖了寂寞  阅读(250)  评论(0编辑  收藏  举报