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);
    }
    

      

  • 相关阅读:
    MFC中实现LISTCRTL控件选中多行进行删除操作
    如何使属性值为“只读”(readonly)的EDIT控件在获取焦点后不显示光标?
    crm 使用stark组件
    ModelForm组件
    自定义admin管理工具(stark组件)
    Django-admin管理工具
    Django-session中间件源码简单分析
    基于角色的权限管理
    ajax参数补充
    datetime模块
  • 原文地址:https://www.cnblogs.com/Browneyes/p/6170595.html
Copyright © 2011-2022 走看看