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

    这里写图片描述

  • 相关阅读:
    [HihoCoder1259]A Math Problem
    [POJ1205]Water Treatment Plants
    [HDU5492]Find a path
    [USACO08JAN]Cell Phone Network
    [CodeForces-543D]Road Improvement
    [HAOI2012]外星人
    [CodeForces-869C]The Intriguing Obsession
    [CodeChef-CAPTCITI]Snakes capturing the Mongoose Cities
    CF741D Arpa’s letter-marked tree and Mehrdad’s Dokhtar-kosh paths
    Luogu P4095 [HEOI2013]Eden的新背包问题
  • 原文地址:https://www.cnblogs.com/laohaozi/p/12538204.html
Copyright © 2011-2022 走看看