windows下多线程互斥量控制简单例子

 //在ReleaseMutex()之前sleep(),sleep()也会释放互斥量。

//这是2个线程模拟卖火车票的小程序
#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=10;
HANDLE hMutex;
int main()
{
    HANDLE hThread1;
    HANDLE hThread2;
  
 
    //创建互斥对象
    hMutex=CreateMutex(NULL,TRUE,"tickets");//TRUE 表示当前线程拥有该互斥量,等下要先释放 tickets为互斥量名称
    if (hMutex)
    {
        if (ERROR_ALREADY_EXISTS==GetLastError())
        {
            cout<<"only one instance can run!"<<endl;
            return 0;
        }
    }
     //创建线程

    hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
    hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
   
    CloseHandle(hThread1);  
    CloseHandle(hThread2);
    ReleaseMutex(hMutex); //先释放互斥量,因为已经拥有该释放量。 
    Sleep(4000);

    WaitForSingleObject(hMutex,INIFITE);//确保子线程退出才结束main

    ReleaseMutex(hMutex);

    CloseHandle(hMutex);
    cout<<"now is the main thread in running\n";
    system("pause");
    return 0;
}
//线程1的入口函数
DWORD WINAPI Fun1Proc(LPVOID lpParameter)//thread data
{
    while (true)
    {
       
        WaitForSingleObject(hMutex,INFINITE);
        if (tickets>0)
        {
         //cout<<"thread1 is in the region"<<endl;
            Sleep(1);//会释放互斥量hMutex
            cout<<"thread1 sell ticket :"<<tickets--<<endl;
        }
        else
            break;
        ReleaseMutex(hMutex);
    }
 
    return 0;
}
//线程2的入口函数
DWORD WINAPI Fun2Proc(LPVOID lpParameter)//thread data
{
    while (true)
    {
     
        WaitForSingleObject(hMutex,INFINITE);
        if (tickets>0)
        {
            Sleep(1);
            cout<<"thread2 sell ticket :"<<tickets--<<endl;
        }
        else
            break;
        ReleaseMutex(hMutex);
    }
   
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值