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

版权声明:本文为BeyondTechnology原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/BeyondTechnology/archive/2010/08/30/1813090.html