生产者和消费者问题。请问为什么输出会嵌套?谢谢
#include <iostream>#include <windows.h>
using namespace std;
#define P(S) WaitForSingleObject(S, INFINITE)
#define V(S) ReleaseSemaphore(S, 1, NULL)
#define Producers 10
#define Consumers 10
typedef HANDLE semaphore;
semaphore mutex, empty, full;
int h = 1;
struct Buffer
{
int buffer[20];
int in, out;
} buf;
DWORD WINAPI Produce(LPVOID para)
{
while(true)
{
P(empty);
P(mutex);
if((buf.in+1)%20 == buf.out)
{
cout << "缓冲区已满,不能再生产" << endl;
break;
}
cout << "生产者生产出一件产品buffer[" << buf.in << "]" << h << endl;
buf.buffer[buf.in] = h;
h = (h+1)%20;
buf.in = (buf.in+1)%20;
V(mutex);
V(full);
}
return 0;
}
DWORD WINAPI Consum(LPVOID para)
{
while(true)
{
P(full);
P(mutex);
if(buf.in == buf.out)
{
cout << "缓冲区已空,不能再消费" << endl;
break;
}
cout << "消费者消费了一件产品buffer[" << buf.out << "]" << buf.buffer[buf.out] << endl;
buf.out = (buf.out+1)%20;
V(mutex);
V(empty);
}
return 0;
}
int main()
{
HANDLE hThread[Producers+Consumers];
DWORD tid;
int i = 0;
mutex = CreateSemaphore(NULL, 20, 20, NULL);
empty = CreateSemaphore(NULL, 20, 20, NULL);
full = CreateSemaphore(NULL, 0, 20, NULL);
int totalThread = Producers+Consumers;
buf.in = buf.out = 0;
for(i = 0; i < Producers; i++)
{
hThread[i] = CreateThread(NULL,0,Consum,&i,0,&tid);
if(hThread[i])
WaitForSingleObject(hThread[i],10);
}
for(; i < totalThread; i++)
{
hThread[i] = CreateThread(NULL,0,Produce,&i,0,&tid);
if(hThread[i])
WaitForSingleObject(hThread[i],10);
}
return 0;
}