Untitled

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
1.3 kB
5
Indexable
Never
#include <condition_variable>
#include <cstdlib>
#include <iostream>
#include <mutex>
#include <thread>
#include <queue>

using namespace std;

mutex m;
condition_variable notFull;

bool ready = false;

queue<int> st;

int produceData()
{
    int randomNumber = rand() % 1000;
    cout << "Produced Data: " << randomNumber << "\n";
    return randomNumber;
}

void consumeData(int data)
{
    cout << "Consumed Data: " << data << "\n";
}

void consumer(int n)
{
    while (true)
    {
        unique_lock<mutex> lock(m);
        cv.wait(lock, []()
                { return ready; });
        cout << n << " ";
        auto data = st.top();
        st.pop();
        consumeData(data);
        ready = false;
        lock.unlock();
        cv.notify_one();
    }
}

void producer(int n)
{
    while (true)
    {
        unique_lock<mutex> lock(m);
        cout << n << " ";
        auto data = produceData();
        st.push(data);
        ready = true;
        lock.unlock();
        cv.notify_one();
        lock.lock();
        cv.wait(lock, []()
                { return !ready; });
    }
}

void consumerThread(int n)
{
    consumer(n);
}

void producerThread(int n)
{
    producer(n);
}

int main()
{
    thread t1(consumerThread, 0);
    thread t2(producerThread, 1);
    t1.join();
    t2.join();
    return 0;
}