操作系统-信号量C++代码WIN32

#include 
#include 
#include 
#include 
#include 

#define BUFFER_SIZE 5
int buffer[BUFFER_SIZE];
int cnt=0;

HANDLE Mutex,Empty,Full;

void init()
{
	Mutex=CreateMutex(NULL,FALSE,NULL);
	Empty=CreateSemaphore(NULL,5,5,NULL);
	Full=CreateSemaphore(NULL,0,5,NULL);
}

int insert_item(int item,int order)
{
	int flag=-1;
	WaitForSingleObject(Empty,INFINITE);
	WaitForSingleObject(Mutex,INFINITE);
	if(cnt0)
	{
		item=buffer[cnt-1];
		buffer[cnt-1]=0;
		flag=0;
		printf("consumer %d consumed %d\n",order,cnt);
		cnt--;
	}
	ReleaseMutex(Mutex);
	ReleaseSemaphore(Empty,1,NULL);
	return flag;
}

DWORD WINAPI producer(void *param)
{
	srand((unsigned)time(NULL));
	int random;
	while(true)
	{
		Sleep((rand()%10+1)*1000);
		if(insert_item(random,(DWORD)param))
		{
			printf("report error condition\n");
		}
	}
}
DWORD WINAPI consumer(void *param)
{
	srand((unsigned)time(NULL));
	int random;
	while(true)
	{
		Sleep((rand()%10+1)*1000);
		if(remove_item(random,(DWORD)param))
		{
			printf("report error condition\n");
		}
	}
}

int main(int argc,char *argv[])
{
	init();
	static const int sleepTime=1000,producerThs=10,consumerThs=10;
	memset(buffer,0,sizeof buffer);
	DWORD ProducerThreadId[producerThs],ConsumerThreadId[consumerThs];
	HANDLE ProducerThreadHandles[producerThs],ConsumerThreadHandles[consumerThs];
	int i;
	for(i=0;i

你可能感兴趣的:(操作系统-信号量C++代码WIN32)