您的位置:首页 > 编程语言 > C语言/C++

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

2015-07-12 17:20 549 查看
#include <windows.h>
#include <random>
#include <cstring>
#include <ctime>
#include <cstdio>

#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(cnt<BUFFER_SIZE)
	{
		buffer[cnt++]=item;
		flag=0;
		printf("producer %d producer %d\n",order,cnt);
	}
	ReleaseMutex(Mutex);
	ReleaseSemaphore(Full,1,NULL);
	return flag;
}

int remove_item(int &item,int order)
{
	int flag=-1;
	WaitForSingleObject(Full,INFINITE);
	WaitForSingleObject(Mutex,INFINITE);
	if(cnt>0)
	{
		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<producerThs;i++)
	{
		ProducerThreadHandles[i]=CreateThread(NULL,0,producer,(LPVOID)i,0,&ProducerThreadId[i]);
	}
	for(i=0;i<consumerThs;i++)
	{
		ConsumerThreadHandles[i]=CreateThread(NULL,0,consumer,(LPVOID)i,0,&ConsumerThreadId[i]);
	}
	Sleep(sleepTime);
	for(i=0;i<producerThs;i++)
	{
		CloseHandle(ProducerThreadHandles[i]);
		CloseHandle(ConsumerThreadHandles[i]);
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: