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

这里写图片描述

原文地址:https://www.cnblogs.com/laohaozi/p/12538203.html