prodconsmodel.cpp

来自「C++解决的一个生产者消费者模型」· C++ 代码 · 共 94 行

CPP
94
字号
// ProdConsModel.cpp: implementation of the CProdConsModel class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "ServerMFC.h"
#include "ProdConsModel.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CProdConsModel::CProdConsModel(int m_iMaxCapacity)
{
	InitializeCriticalSection(&m_critical);

	this->m_hProductEvent = NULL;
	this->m_hConsumerEvent = NULL;
    this->m_hShutdownEvent = NULL;

	this->m_hProductEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	this->m_hConsumerEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	this->m_hShutdownEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

	ResetEvent(this->m_hProductEvent);
	ResetEvent(this->m_hConsumerEvent);
	ResetEvent(this->m_hShutdownEvent);
    this->m_iMaxCapacity = m_iMaxCapacity;
}

CProdConsModel::~CProdConsModel()
{
	CloseHandle(m_hProductEvent);
	CloseHandle(m_hConsumerEvent);
	CloseHandle(m_hShutdownEvent);

    DeleteCriticalSection(&m_critical);
}

vector<int> CProdConsModel:: pop_back(vector<int> v, int *pitem)
{
    for (int k=0;k<v.size();k++) {
       int *tmp = v.begin()+k;
	   if (*tmp==*pitem) v.erase(tmp);
    }
	return v;
}

//consumer
int CProdConsModel::get()
{
    SetEvent(m_hConsumerEvent);
	while (getClientConnSize()<=0) { //wait
        WaitForSingleObject(m_hProductEvent,INFINITE);
	}
    ResetEvent(m_hConsumerEvent);

	EnterCriticalSection(&m_critical);
	int *pitem =c_vector.begin();
    int var = *pitem;
	c_vector = pop_back(c_vector,pitem);
	LeaveCriticalSection(&m_critical);
	
    return var;
}

//producer
void CProdConsModel::set(int clientSocket)
{
	SetEvent(m_hProductEvent);
	while (getClientConnSize()>m_iMaxCapacity) {
        WaitForSingleObject(m_hConsumerEvent,INFINITE);
	}
    ResetEvent(m_hProductEvent);

	EnterCriticalSection(&m_critical);
    c_vector.push_back(clientSocket);
	LeaveCriticalSection(&m_critical);
}

int CProdConsModel::getClientConnSize()
{
	EnterCriticalSection(&m_critical);
	int size = c_vector.size();
	LeaveCriticalSection(&m_critical);
	return size;
}

⌨️ 快捷键说明

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