生产者消费者模型

来源:互联网 发布:淘宝网商城儿童女装 编辑:程序博客网 时间:2024/06/08 06:32


ProducerCustomer.h
#ifndef PRODUCERCUSTOMER_H#define PRODUCERCUSTOMER_H#include <Windows.h>#include <vector>using std::vector;class ProducerCustomer{public:    ProducerCustomer();    void Produce();    void Customer();private:    vector<int> m_oStore;    // 与仓库对应    HANDLE m_pStoreEmpty;    HANDLE m_pStoreFull;    HANDLE m_pMutex;    int m_nIndex;};#endif // PRODUCERCUSTOMER_H



ProducerCustomer.cpp

#include <iostream>#include "ProducerCustomer.h"using namespace std;const int c_MaxStore    = 20;ProducerCustomer::ProducerCustomer() :    m_oStore(),    m_pStoreEmpty(NULL),    m_pStoreFull(NULL),    m_pMutex(NULL),    m_nIndex(0){    m_pStoreEmpty = CreateSemaphoreA(NULL, c_MaxStore, c_MaxStore, NULL);    m_pStoreFull = CreateSemaphoreA(NULL, 0, c_MaxStore, NULL);    m_pMutex = CreateMutexA(NULL, false, NULL);}/*void Productor() {    while(1) {        //制造数据        P(&empty);        P(&mutex);        //填充数据        V(&mutex);        V(&full);    }}void Consumer() {    while(1) {        P(&full);        P(&mutex);        //消费数据        V(&mutex);        V(&empty);    }}*/void ProducerCustomer::Produce(){//    while (true)//    {        WaitForSingleObject(m_pStoreEmpty, INFINITE);        WaitForSingleObject(m_pMutex, INFINITE);        m_oStore.push_back(++m_nIndex);        cout << "生产: " << m_nIndex << endl;        ReleaseMutex(m_pMutex);        ReleaseSemaphore(m_pStoreFull, 1, NULL);//    }}void ProducerCustomer::Customer(){//    while (true)//    {        WaitForSingleObject(m_pStoreFull, INFINITE);        WaitForSingleObject(m_pMutex, INFINITE);        cout << "\t\t消费: " << m_oStore[m_oStore.size() - 1] << endl;        m_oStore.pop_back();        ReleaseMutex(m_pMutex);        ReleaseSemaphore(m_pStoreEmpty, 1, NULL);//    }}



main.cpp

#include <iostream>#include <vector>#include <boost/thread.hpp>#include "ProducerCustomer.h"int main(int argc, char *argv[]){    ProducerCustomer oProCus;    boost::thread_group oProGroup;    boost::thread_group oCusGroup;    for (int i = 0; i < 40; i++)    {        oProGroup.create_thread(boost::bind(&ProducerCustomer::Produce, &oProCus));        //boost::this_thread::sleep(boost::posix_time::seconds(1));        oCusGroup.create_thread(boost::bind(&ProducerCustomer::Customer, &oProCus))    ;    }    oProGroup.join_all();    oCusGroup.join_all();    return 0;}