⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 test1.cpp

📁 操作系统经典同步问题 消费者与生产者问题
💻 CPP
字号:
#include <stdlib.h>#include <stdio.h>#include <windows.h>typedef int buffer_item;#define BUFFER_SIZE 5buffer_item buffer[BUFFER_SIZE];int count=0,in=0,out=0;bool producer_done = 0;HANDLE sem_full;		HANDLE sem_empty;		HANDLE sem_mutex;DWORD WINAPI producer(LPVOID arg){	buffer_item num;	for(int p=0;p<=10;p++)	{		num=rand()%RAND_MAX;		WaitForSingleObject(sem_empty,INFINITE);        WaitForSingleObject(sem_mutex,INFINITE);         buffer[in]=num;	    in=(in+1)%BUFFER_SIZE;	    count++;		printf("producer produced %d\n",num);		ReleaseSemaphore(sem_mutex,1,NULL);        ReleaseSemaphore(sem_full,1,NULL); 	}	WaitForSingleObject(sem_mutex,INFINITE);
    producer_done = 1;
    ReleaseSemaphore(sem_mutex,1,NULL);	return 0;}DWORD WINAPI consumer(LPVOID arg){	buffer_item num;	for(int p=0;p<=10;p++)	{		WaitForSingleObject(sem_mutex,INFINITE);		        if (count<=0 && producer_done)	    {	       ReleaseSemaphore(sem_mutex,1,NULL);	       break;	    }        ReleaseSemaphore(sem_mutex,1,NULL);	    WaitForSingleObject(sem_full,INFINITE);        WaitForSingleObject(sem_mutex,INFINITE);		        num=buffer[out];		out=(out+1)%BUFFER_SIZE;		count--;		printf("consumer consumed %d\n",num);		ReleaseSemaphore(sem_mutex,1,NULL);
		ReleaseSemaphore(sem_empty,1,NULL);	}	return num; }int main(){	int i;
	sem_mutex=CreateSemaphore(NULL,1,1,NULL);
	sem_full=CreateSemaphore(NULL,0,5,NULL);
	sem_empty=CreateSemaphore(NULL,5,5,NULL);	for( i=0;i<BUFFER_SIZE;i++)	      buffer[i]=0;	HANDLE pro,con;
	for( i=0;i<11;i++)
	{
		printf("This is No. %d producer\n",i);
	    pro=CreateThread(NULL,0,producer,NULL,0,NULL);
    }
	for( i=0;i<11;i++)
	{
		printf("This is No. %d consumer\n",i);
	    pro=CreateThread(NULL,0,consumer,NULL,0,NULL);
    }
	for( i=0;i<11;i++)
	   WaitForSingleObject(pro,INFINITE);
	for( i=0;i<11;i++)
	   WaitForSingleObject(con,INFINITE);
	return 0;}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -