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;
    }

    这里写图片描述

  • 相关阅读:
    关于Quartz .NET(V3.0.7)的简要说明
    .NET实现一个简单的IOC容器
    .NET中的控制反转及AutoFac的简单说明
    .NET异步程序设计——async&await
    .NET异步程序设计——任务并行库
    .NET异步程序设计——异步委托
    .NET异步程序设计——概念引入
    关于C#程序的单元测试
    关于Log4Net的使用及配置方式
    基于.net ,使用几种常见的NoSQL数据库
  • 原文地址:https://www.cnblogs.com/laohaozi/p/12538203.html
Copyright © 2011-2022 走看看