zoukankan      html  css  js  c++  java
  • 15.4.1火车站售票系统模拟程序(Mutex)

    #include <iostream>
    #include <Windows.h>
    using namespace std;

    int tickets = 100;
    HANDLE hMutex;

    DWORD WINAPI ThreadProc1(LPVOID lpParameter);

    DWORD WINAPI ThreadProc2(LPVOID lpParameter);

    int main()
    {
        hMutex = CreateMutex(NULL,FALSE,NULL);
        HANDLE hThread1 = CreateThread(NULL,0,ThreadProc1,NULL,0,NULL);
        HANDLE hThread2 = CreateThread(NULL,0,ThreadProc2,NULL,0,NULL);
        DWORD nCount = 2;
        HANDLE* lpHandles = new HANDLE[2];
        lpHandles[0] = hThread1;
        lpHandles[1] = hThread2;
        WaitForMultipleObjects(nCount,lpHandles,TRUE,INFINITE);
        CloseHandle(hThread1);
        CloseHandle(hThread2);
        return 0;
    }

    DWORD WINAPI ThreadProc1(LPVOID lpParameter)
    {
        while(true)
        {
            WaitForSingleObject(hMutex,INFINITE);
            if (tickets > 0)
            {
                cout<<"Thread1 sells "<<tickets--<<endl;
                ReleaseMutex(hMutex);
            }
            else
            {
                ReleaseMutex(hMutex);
                break;
            }
        }
        return 0;
    }

    DWORD WINAPI ThreadProc2(LPVOID lpParameter)
    {
        while(true)
        {
            WaitForSingleObject(hMutex,INFINITE);
            if (tickets > 0)
            {
                cout<<"Thread2 sells "<<tickets--<<endl;
                ReleaseMutex(hMutex);
            }
            else
            {
                ReleaseMutex(hMutex);
                break;
            }
        }
        return 0;
    }

  • 相关阅读:
    Python [Leetcode 350]Intersection of Two Arrays II
    jade学习
    pageX、clientX、screenX、offsetX、layerX、x
    AngularJS--转载
    AngularJS
    超级强大的SVG动画详解
    javascript event对象的clientX,offsetX,screenX,pageX区别
    console的调试方法
    javascript--函数参数与闭包--详解
    如何把你的图标转换成web字体
  • 原文地址:https://www.cnblogs.com/BeyondTechnology/p/1813090.html
Copyright © 2011-2022 走看看