I’m trying to learn threading in C++ and not able to understand why both threads are not running one after the other? After push, the mutex is unlocked and notified through condition variable.
Why is pop thread not executing at the point? It can access the queue as the mutex is unlocked and pop the inserted value. But instead what I’m seeing is that push thread runs till the queue is full and after that pop thread runs till the queue is empty.
#include <iostream>
#include <thread>
#include <future>
#include <queue>
using namespace std;
template<typename E>
class BlockingQueue
{
private:
size_t mMaxSize;
queue<E> mQueue;
mutex mtx;
condition_variable mConditionVar;
public:
BlockingQueue(size_t size): mMaxSize{size}
{
}
void push(E element)
{
unique_lock<mutex> pushLock(mtx);
mConditionVar.wait(pushLock, [this](){ return mQueue.size() < mMaxSize; });
cout << "Pushing " << element << endl;
mQueue.push(element);
pushLock.unlock();
mConditionVar.notify_one();
}
void pop()
{
unique_lock<mutex> popLock(mtx);
mConditionVar.wait(popLock, [this](){ return mQueue.size() > 0; });
cout << "Popping " << mQueue.front() << endl;
mQueue.pop();
popLock.unlock();
mConditionVar.notify_one();
}
E front()
{
return mQueue.front();
}
size_t size()
{
return mQueue.size();
}
};
int main()
{
BlockingQueue<int> bq(5);
thread t1([&](){
for (int i = 1; i <= 10; i++)
bq.push(i);
});
thread t2([&](){
for (int i = 1; i<=10; i++)
bq.pop();
});
t1.join();
t2.join();
return 0;
}