zoukankan      html  css  js  c++  java
  • 生产者消费者问题 一个生产者 两个消费者 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("生产者完成任务,线程结束运行
    ");  
    	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的消费者收到通知,线程结束运行
    ", 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);
    }
    

      

  • 相关阅读:
    Mysql 权限命令整理大全
    阿里云ECS发送邮件失败
    彻底删除Kafka中的topic
    mysql Slave 启动失败
    mysql双主热备
    mysql 主从笔记
    mysql主从同步的键值冲突问题的解决方法
    python0.2----如何在windows下搭建最简洁的python环境
    内存0.1---内存里数据的表示形式以及进制转换
    python0.1-----pyhon的优缺点,为何学习python
  • 原文地址:https://www.cnblogs.com/Browneyes/p/6170595.html
Copyright © 2011-2022 走看看