#include<iostream>
#include<Windows.h>
#include<process.h>
using namespace std;
int mutex1 = 1,//处理线程互斥
site = 10, //最多允许10个线程等待处理
customer = 0,//现在处理线程的数目
mutex2=1;//等待处理的线程之间互斥
int p(int* s)//信号量p操作
{
while (*s <= 0)Sleep(100);//这里不加sleep(100)就不行,很神奇
(*s) -= 1;
return 0;
}
int v(int* s)//信号量v操作
{
(*s)+=1;
return 0;
}
void process1(void*)//服务线程
{
while (1)
{
p(&customer);
p(&mutex1);
cout << "为顾客" << customer+1 << "服务"<<endl;
v(&mutex1);
v(&site);
Sleep(1000);
}
}
void customers(void*)//用户线程
{
p(&site);
p(&mutex2);
cout << "取号座位为" <<10- site << endl;
v(&mutex2);
v(&customer);
_endthread();
}
int main()
{
_beginthread(process1,0,NULL
);
while (1)
{
_beginthread(customers, 0, NULL
);
Sleep(100);
if (customer > 9)//用户线程满了,就等一会
{
Sleep(10000);
}
}
getchar();
return 0;
}