生产者消费者问题 一个生产者 两个消费者 4个缓冲区 生产10个产品

#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <process.h>

using namespace std;

int buffer[4];
int iCountOfProduct=10;

HANDLE hSemaphoreFull;
HANDLE hSemaphoreEmpty;
int gi=0;
int gj=0;

CRITICAL_SECTION  g_cs;
unsigned int __stdcall Producter(LPVOID p)
{
	for(int i=1;i<=iCountOfProduct;i++)
	{
		WaitForSingleObject(hSemaphoreEmpty,INFINITE);
		EnterCriticalSection(&g_cs);
		buffer[gi]=i;
		cout<<"生产者放入 "<<"缓冲池:"<<gi<<"数据:"<<buffer[gi]<<endl;
		gi=(gi+1)%4;
		LeaveCriticalSection(&g_cs);
		ReleaseSemaphore(hSemaphoreFull,1,NULL);
	}
	printf("生产者完成任务,线程结束运行\n");  
	return 0;
}

unsigned int __stdcall Customer(LPVOID p)
{
	while(true)
	{
		WaitForSingleObject(hSemaphoreFull,INFINITE);
		EnterCriticalSection(&g_cs);
		cout<<"消费者读取 " <<"缓冲池:"<<gj<<"数据:"<<buffer[gj]<<endl;

		if (buffer[gj] == iCountOfProduct)//结束标志  
        {  
            LeaveCriticalSection(&g_cs);  
            //通知其它消费者有新数据了(结束标志)  
            ReleaseSemaphore(hSemaphoreFull, 1, NULL);  
            break;  
        }  

		gj=(gj+1)%4;
		LeaveCriticalSection(&g_cs);
		ReleaseSemaphore(hSemaphoreEmpty,1,NULL);
	}
	printf("  编号为%d的消费者收到通知,线程结束运行\n", GetCurrentThreadId()); 
	return 0;
}

void main()
{
	HANDLE hThread[3];
	InitializeCriticalSection(&g_cs);

	hSemaphoreFull=CreateSemaphore(NULL,0,4,NULL);
	hSemaphoreEmpty=CreateSemaphore(NULL,4,4,NULL);
	hThread[0]=(HANDLE)_beginthreadex(NULL,0,Producter,NULL,0,0);
	hThread[1]=(HANDLE)_beginthreadex(NULL,0,Customer,NULL,0,0);
	hThread[2]=(HANDLE)_beginthreadex(NULL,0,Customer,NULL,0,0);
	WaitForMultipleObjects(3,hThread,TRUE,INFINITE);
	for(int i=0;i<3;i++)
	{
		CloseHandle(hThread[i]);
	}
	CloseHandle(hSemaphoreFull);
	CloseHandle(hSemaphoreEmpty);
}

  

转载于:https://www.cnblogs.com/Browneyes/p/6170595.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值