特注:运行该程序需要设置VC6.0环境
Project->Setting->C/C++->Category->Code Generation->Using Run-time library->Debug MultiThreaded
#include <iostream>
#include <list>
#include <windows.h>
#include <process.h>
using namespace std;
#define P(sem) WaitForSingleObject(sem,INFINITE)
#define V(sem) ReleaseSemaphore(sem,1,NULL)
class CQueue
{
public:
void addTail();//往队列尾部增加一个元素
void removeHead();//读出并移除队列的第一个元素
private:
list<int> L;
};
CQueue buffer;//全局的缓冲区
const int buf_size = 10;//缓冲区大小
static int GOODS_ID = 0;//商品序号
const int producers = 3;//生产者数量
const int consumers = 8;//消费者数量
void ProducerThread(void* param);
void ConsumerThread(void* param);
HANDLE empty,occupy,op_mutex;
int main()
{
int i;
int p_id[producers],c_id[consumers];
occupy = CreateSemaphore(NULL,0,buf_size,NULL);//占用位置
empty = CreateSemaphore(NULL,buf_size,buf_size,NULL);//空余位置
op_mutex = CreateSemaphore(NULL,1,1,NULL);//操作互斥量
for(i=0;i<producers;++i)
{
p_id[i] = i+1;
_beginthread(ProducerThread,0,p_id+i);
}
for(i=0;i<consumers;++i)
{
c_id[i] = i+1;
_beginthread(ConsumerThread,0,c_id+i);
}
while(getchar()=='\n') break;
return 0;
}
void CQueue::addTail()
{
L.insert(L.end(),++GOODS_ID);
}
void CQueue::removeHead()
{
cout<<*L.begin()<<endl;
L.erase(L.begin());
}
void ProducerThread(void* param)
{
int id = *(int*)param;
while(1)
{
P(empty);
P(op_mutex);
Sleep(100);
buffer.addTail();
printf("Producer_%d produced %d\n",id,GOODS_ID);
V(op_mutex);
V(occupy);
}
}
void ConsumerThread(void* param)
{
int id = *(int*)param;
while(1)
{
P(occupy);
P(op_mutex);
Sleep(100);
printf("Consumer_%d consumed ",id);
buffer.removeHead();
V(op_mutex);
V(empty);
}
}