BAT面试题:请写一个有关生产者消费者队列通信的模型:
HANDLE ghSemaphore; //信号量
const int gMax = 100; //生产(消费)总数
std::queue<int> q; //生产入队,消费出队
//生产者线程
unsigned int __stdcall producerThread(void* pParam)
{
int n = 0;
while(++n <= gMax)
{
//生产
q.push(n);
cout<<"produce "<<n<<endl;
ReleaseSemaphore(ghSemaphore, 1, NULL); //增加信号量
Sleep(300);//生产间隔的时间,可以和消费间隔时间一起调节
}
_endthread(); //生产结束
return 0;
}
//消费者线程
unsigned int __stdcall customerThread(void* pParam)
{
int n = gMax;
while(n--)
{
WaitForSingleObject(ghSemaphore, 10000);
//消费
q.pop();
cout<<"custom "<<q.front()<<endl;
Sleep(500);//消费间隔的时间
}
//消费结束
CloseHandle(ghSemaphore);
cout<<"working end."<<endl;
_endthread();
return 0;
}
//信号量来维护线程同步
ghSemaphore =
CreateSemaphore(NULL, 0, gMax, NULL);
Copyright 2011-2020 © MallocFree. All rights reserved.