麻烦大家帮我看看消费者与生产者,我的程序哪出了问题
#include <windows.h>#include <iostream>
using namespace std;
#include <malloc.h>
#define BUFFERSIZE 8
template<class T>
class Queue
{
T *data;
int front,rear;
int curlen;
public:
Queue():front(0),rear(0),curlen(0)
{
data = (T*)malloc(sizeof(T)*BUFFERSIZE);
}
void EnQue(T x)
{
if(isfull()) return;
data[rear++] = x;
rear = rear%8;
curlen++;
}
void DeQueue(T &x)
{
if(isempty()) return;
x=data[front];
front = (front+1)%8;
curlen--;
}
T GetTop()
{
}
bool isempty()
{
return (curlen == 0);
}
bool isfull()
{
return (curlen == 8);
}
~Queue()
{
if(data != NULL)
{
free(data);
data = NULL;
curlen = front = rear = 0;
}
}
};
Queue<int> qu;
HANDLE pro;
HANDLE con;
HANDLE s;
DWORD _stdcall producer(LPVOID)
{
for(int i=0; i < 20; i++)
{
WaitForSingleObject(s,-1);
if(qu.isfull())
{
WaitForSingleObject(pro,-1); //等待pro变为大于0
}
qu.EnQue(i);
printf("生产 %d\n",i);
ReleaseSemaphore(con,1,NULL);
ReleaseSemaphore(s,1,NULL);
}
WaitForSingleObject(s,-1);
qu.EnQue(-1);
printf("生产结束\n");
ReleaseSemaphore(con,1,NULL);
ReleaseSemaphore(s,1,NULL);
return 0;
}
DWORD _stdcall consumer(LPVOID)
{
int x;
for(;;)
{
WaitForSingleObject(s,-1);
if(qu.isempty())
{
WaitForSingleObject(con,-1); //等待con变为大于0
}
qu.DeQueue(x);
if(x == -1)
break;
printf("消费 %d\n",x);
ReleaseSemaphore(pro,1,NULL);
ReleaseSemaphore(s,1,NULL);
}
printf("消费结束\n");
ReleaseSemaphore(s,1,NULL);
return 0;
}
int main()
{
pro = CreateSemaphore(NULL,1,1,NULL);
con = CreateSemaphore(NULL,0,1,NULL);
s = CreateSemaphore(NULL,2,2,NULL);
HANDLE hThrds[2];
DWORD id;
hThrds[0] = CreateThread(NULL,0,producer,NULL,-1,&id);
hThrds[1] = CreateThread(NULL,0,consumer,NULL,-1,&id);
WaitForMultipleObjects(2,hThrds,true,-1);
CloseHandle(hThrds[0]);
CloseHandle(hThrds[1]);
return 0;
}