c++11 單生產者單消費者模式

注意:

  1. 向標準緩衝區輸出字符串時,由於是多線程的,所以需要使用讀寫鎖來同步
  2. 使用了一個deque的隊列作爲倉庫緩衝區,尾部存放頭部取出
  3. 當單單模式變成多多模式時,只是針對單變多的某一方多添加一個讀寫鎖
  4. 需要用到C++11中的 互斥鎖、條件變量確保多線程間的數據同步

1、單生產者單消費者模式:

  • 顧名思義,單生產者-單消費者模型中只有一個生產者和一個消費者:
  • 生產者不停地往產品庫中放入產品;
  • 消費者則從產品庫中取走產品;
  • 產品庫容積有限制,只能容納一定數目的產品;
  • 如果生產者生產產品的速度過快,則需要等待消費者取走產品之後,產品庫不爲空才能繼續往產品庫中放置新的產品;
  • 相反,如果消費者取走產品的速度過快,則可能面臨產品庫中沒有產品可使用的情況,此時需要等待生產者放入一個產品後,消費者才能繼續工作。
#include <thread>
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <deque>
using namespace std;

static const int kItemsToProduce = 20;//定義生產者能夠生產的最大產品個數
std::mutex stdoutMutex;//多線程標準輸出 同步鎖

struct ItemRepository
{
    deque<int> itemQueue;   // 這裏用隊列代表倉庫緩衝區
    int MaxSize = 10;       // 倉庫所容納的產品最大個數
    std::mutex mtx;         // 互斥量,保護產品緩衝區
    std::condition_variable repository_notFull;     // 條件變量, 指產品倉庫緩衝區不爲滿
    std::condition_variable repository_notEmpty;    // 條件變量, 指產品倉庫緩衝區不爲空
}gItemRepository;   // 產品庫全局變量,生產者和消費者操作該變量.

typedef struct ItemRepository ItemRepository;


// 生產 產品
void ProduceItem(ItemRepository &itemRepo, int item)
{
    std::unique_lock<std::mutex> lock(itemRepo.mtx);
    while (itemRepo.itemQueue.size()>=itemRepo.MaxSize) // 判斷當前倉庫滿了
    {
        {
            std::lock_guard<std::mutex> lock(stdoutMutex);
            cout << "倉庫滿了,生產者等待中..." <<"thread id = "<< std::this_thread::get_id() << endl;
        }
        itemRepo.repository_notFull.wait(lock); // 等待信號量釋放鎖 生產者等待"倉庫緩衝區不爲滿"這一條件發生(將會跳出循環).
    }
    itemRepo.itemQueue.push_back(item);         // 倉庫放入產品
    itemRepo.repository_notEmpty.notify_all();  // 通知消費者倉庫不爲空
    lock.unlock();  // 釋放鎖
}

// 消費 產品
int ConsumeItem(ItemRepository &itemRepo)
{
    int data;
    std::unique_lock<std::mutex> lock(itemRepo.mtx);
    while (itemRepo.itemQueue.empty())  // 判斷當前倉庫空了,等待
    {
        {
            std::lock_guard<std::mutex> lock(stdoutMutex);
            cout << "倉庫空了,消費者等待中..." << "thread id = " << std::this_thread::get_id() << endl;
        }
        itemRepo.repository_notEmpty.wait(lock);// 消費者等待"倉庫緩衝區不爲空"這一條件發生.(等待信號跳出循環)
    }

    data = itemRepo.itemQueue.front();
    itemRepo.itemQueue.pop_front();
    itemRepo.repository_notFull.notify_all();
    lock.unlock();
    return data;
}

// 生產者任務
void ProducerTask()
{
    for (int i = 1;i <= kItemsToProduce;++i)
    {   
        ProduceItem(gItemRepository, i);    // 生產產品
        {
            std::lock_guard<std::mutex> lock(stdoutMutex);
            cout << "Produce the " << i << " ^th item..." << endl;
        }
    }
}

// 消費者任務
void ConsumerTask()
{
    static int cnt = 0;
    while (true)
    {
        //this_thread::sleep_for(std::chrono::seconds(1));
        int item = ConsumeItem(gItemRepository);    // 消費產品
        {
            std::lock_guard<std::mutex> lock(stdoutMutex);
            cout << "Consume the " << item << "^th item..." << endl;
        }
        if (++cnt == kItemsToProduce) break;    // 當消費產品數量 == 生產的數量 退出
    }
}

int main()
{

    std::thread producer(ProducerTask);
    std::thread consumer(ConsumerTask);

    producer.join();
    consumer.join();

    system("pause");
    return 0;
}

Produce the 1 ^th item...
Produce the 2 ^th item...
Produce the 3 ^th item...
Produce the 4 ^th item...
Produce the 5 ^th item...
Produce the 6 ^th item...
Produce the 7 ^th item...
Produce the 8 ^th item...
Produce the 9 ^th item...
Produce the 10 ^th item...
倉庫滿了,生產者等待中...
Consume the 1^th item...
Produce the 11 ^th item...
倉庫滿了,生產者等待中...
Consume the 2^th item...
Produce the 12 ^th item...
倉庫滿了,生產者等待中...
Consume the 3^th item...
Produce the 13 ^th item...
倉庫滿了,生產者等待中...
Consume the 4^th item...
Produce the 14 ^th item...
倉庫滿了,生產者等待中...
Consume the 5^th item...
Produce the 15 ^th item...
倉庫滿了,生產者等待中...
Consume the 6^th item...
Produce the 16 ^th item...
倉庫滿了,生產者等待中...
Consume the 7^th item...
Produce the 17 ^th item...
倉庫滿了,生產者等待中...
Consume the 8^th item...
Produce the 18 ^th item...
倉庫滿了,生產者等待中...
Consume the 9^th item...
Produce the 19 ^th item...
倉庫滿了,生產者等待中...
Consume the 10^th item...
Produce the 20 ^th item...
Consume the 11^th item...
Consume the 12^th item...
Consume the 13^th item...
Consume the 14^th item...
Consume the 15^th item...
Consume the 16^th item...
Consume the 17^th item...
Consume the 18^th item...
Consume the 19^th item...
Consume the 20^th item...
可以用 lambda 進行替換

    // 等待信號不爲空的通知,wait 第二參數爲true時 向下執行,否則一直等待
    itemRepo.repository_notEmpty.wait(lock, [&itemRepo] {
        bool empty = itemRepo.itemQueue.empty();
        if(empty)
            cout << "倉庫空了,消費者等待中..." << "thread id = " << std::this_thread::get_id() << endl;
        return !empty;
    });


    itemRepo.repository_notFull.wait(lock, [&itemRepo] {
        bool full = itemRepo.itemQueue.size() >= itemRepo.MaxSize;
        if(full)
            cout << "倉庫滿了,生產者等待中..." << "thread id = " << std::this_thread::get_id() << endl;
        return !full;
    });
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章