多线程

#include<windows.h>
#include<iostream.h>

DWORD WINAPI Fun1Proc(LPVOID lpParameter); //声明线程函数1

int tickets=100; //初始化车票的数量
HANDLE hMutex; //定义线程互斥对象
void main()
{
HANDLE hThread1; //定义线程hThread1
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL); //创建线程hThread1
CloseHandle(hThread1); //关闭线程句柄,
cout<<"main thread is running!"<<endl;
hMutex=CreateMutex(NULL,FALSE,NULL); //初始化线程互斥对象
while(1)
{
WaitForSingleObject(hMutex,INFINITE); //等待互斥对象
if(tickets>0)//如果车票数量大于0则卖票,车票数量减一
{
cout<<"main thread sell tickets:"<<tickets<<endl;
tickets--;
}

else
break; //若车票卖光了,则跳出while循环

ReleaseMutex(hMutex); //主线程卖出一张票后,释放线程互斥对象
}
}
DWORD WINAPI Fun1Proc(LPVOID lpParameter) //定义线程1的处理函数
{
cout<<" thread1 is running!"<<endl;
while(1)
{
WaitForSingleObject(hMutex,INFINITE); //等待线程互斥对象
if(tickets>0) //若车票没卖完,则卖票,车票数减一
{

cout<<"thread1 sell tickets:"<<tickets<<endl;
tickets--;
}

else
break; //否则跳出while循环
ReleaseMutex(hMutex); //卖票成功,释放线程互斥对象
}
return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值