C++生產(chǎn)者消費者

// Dexic.cpp: 定義控制臺應(yīng)用程序的入口點。
//

#include "stdafx.h"
#include <Windows.h>
#include <mutex>    
#include <condition_variable>
#include <deque>
#include <iostream>
using namespace std;

std::condition_variable QueueNotFull;
std::condition_variable QueueNotEmpty;
std::mutex QueueMutex;
std::deque<int> Que;
const int MaxSize = 10;

bool isEmpty() {
    return Que.empty();
}

bool isFull() {
    return Que.size() == MaxSize;
}

void dataPut(int element) {
    std::unique_lock<std::mutex> locker(QueueMutex);
    while (isFull() )
    {
        cout << "Queue is Full !!" << endl;
        QueueNotFull.wait(locker);

    }
    Que.push_back(element);
    QueueNotEmpty.notify_all();
}
int dataGet() {
    std::unique_lock<std::mutex> locker(QueueMutex);
    while (isEmpty())
    {
        cout << "Queue is Empty !!" << endl;
        QueueNotEmpty.wait(locker);
        Sleep(1000);
    }
    int t = Que.front();
    Que.pop_front();
    QueueNotFull.notify_all();
    return t;


}

void getFunc() {
    while (1) {
        int var;
        var = dataGet();
        cout << "Get data :" << var << endl;
        Sleep(1000);

    }
}

void putFunc() {
    //srand((unsigned int)time(0));
    int i = 0;
    while (i < 100) {
        dataPut(i++);
        //int var = rand() % 100;
        //dataPut(var);

    }
}

int main(int arc, char** argv)
{
    cout << "Hello World" << endl;
    std::thread td1(getFunc);
    std::thread td2(putFunc);
    td1.join();
    td2.join();
    return 0;
}



image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 練習(xí)第五張水彩多肉,興致勃勃的從肉友那里挖來一張美美肉肉的圖,結(jié)果被我一張水彩給畫殘了-_-# 畫到一半想放棄呢,...
    來一盤肉肉閱讀 477評論 6 5
  • 小花生活在山石組成的路上,環(huán)境是那么的惡劣,可是小花人就開出金黃色的花朵,給人溫暖,個人力量。金黃色的微笑是溫暖的...
    清風幻月閱讀 362評論 0 0
  • 今天是7月1日,高二期末考試日,還有一個小時就要考試了,我在教室里轉(zhuǎn)了一圈又一圈,舍不得離開,我比學(xué)生還要...
    范祎琳1988閱讀 194評論 0 1
  • 汝于此, 吾竭盡所能靜靜眺望。 汝未此, 吾失魂落魄感嘆炎涼。 人海茫茫 吾予卿本佳人相守望。 吾不言, 吾言之樂...
    Darren達倫閱讀 463評論 0 1

友情鏈接更多精彩內(nèi)容