zoukankan      html  css  js  c++  java
  • C++ 多线程 火车站售票

    #include <windows.h>
    #include <iostream.h>
    
    DWORD WINAPI Fun1Proc(
        LPVOID lpParameter //thread data
    );
    
    DWORD WINAPI Fun2Proc(
                          LPVOID lpParameter //thread   data
    );
    
    int index = 0;
    int tickets = 100;
    HANDLE hMutex;
    
    void main()
    {
        HANDLE hThread1;
        HANDLE hThread2;
    
    
        // 仅允许有一个实列运行
        hMutex = CreateMutex(NULL, FALSE, "tickets");
        if (hMutex){
            DWORD dw = GetLastError();
            if (ERROR_ALREADY_EXISTS == dw){
                cout<<"only one instance can run!!"<<endl;
                return;
            }
        }
    
        // 创建线程
        hThread1 = CreateThread(NULL,0,Fun1Proc, NULL, 0, NULL);
        hThread2 = CreateThread(NULL,0,Fun2Proc, NULL, 0, NULL);
        CloseHandle(hThread1);
        CloseHandle(hThread2);
    
        // 创建互斥对像
        //hMutex = CreateMutex(NULL,TRUE,NULL);
        //WaitForSingleObject(hMutex,INFINITE);
        //ReleaseMutex(hMutex);
        //ReleaseMutex(hMutex);
    
        Sleep(4000);
    }
    
    //线程1入口
    DWORD WINAPI Fun1Proc(LPVOID lpParameter ){
    //  WaitForSingleObject(hMutex,INFINITE);
    //  cout<<"thread 1 run"<<endl;
    //  return 0;
        //WaitForSingleObject(hMutex, INFINITE);
        while(TRUE){
            // 无限等待
            WaitForSingleObject(hMutex, INFINITE);
            if (tickets > 0){
                //Sleep(20);
                cout<<"thread1 sell ticket:"<<tickets--<<endl;
            }else{
                break;
            }
            // 释放对像
            ReleaseMutex(hMutex);
        }
        //ReleaseMutex(hMutex);
        return 0;
    }
    
    //线程2入口
    DWORD WINAPI Fun2Proc(LPVOID lpParameter ){
    //  WaitForSingleObject(hMutex,INFINITE);
    //  cout<<"thread 2 run"<<endl;
    //  return 0;
        while(TRUE){
            WaitForSingleObject(hMutex, INFINITE);
            if (tickets > 0){
                //Sleep(40);
                cout<<"thread2 sell ticket:"<<tickets--<<endl;
            }else{
                break;
            }
            ReleaseMutex(hMutex);
        }
        return 0;
    }

    这里写图片描述

  • 相关阅读:
    python起航
    【Git】rebase 用法小结
    使用AutoJs编写UI的踩坑记录
    cpu性能消耗分析
    python自动安装依赖模块_python模块管理:如何自动生成和安装requirements.txt依赖...
    Office Tools Plus
    Git 仓库基础操作
    jmeter-阶梯式压测
    JMeter ServerAgent服务器资源监控插件
    Fastjson 从JSON字符串中取值 操作示例
  • 原文地址:https://www.cnblogs.com/laohaozi/p/8266525.html
Copyright © 2011-2022 走看看