C++生产者消费者

2018-10-16  本文已影响16人  g0
// Dexic.cpp: 定义控制台应用程序的入口点。
//

#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
上一篇 下一篇

猜你喜欢

热点阅读