Search code examples
c++multithreadingcondition-variable

ThreadSafe Queue c++


I am trying to make a thread safe queue in c++ with the help of std::mutex and std::condition_variable.The Code

#include <iostream>
#include<thread>
#include<queue>
#include<atomic>
#include<mutex>
#include<condition_variable>

using namespace std;

template<class T>
class SafeQueue{
public:
    queue<T>qu;
    mutex mut;
    condition_variable cv;
    SafeQueue(){}
    SafeQueue(queue<T>q):qu(q){}
    void push(int val){
        unique_lock<mutex>uq(mut);
        cv.wait(uq,[&](){return qu.empty();});
        qu.push(val);
        uq.unlock();
    }
    bool isEmpty(){
//      unique_lock<mutex>uq(mut);
//      uq.unlock();
        cv.notify_all();
        return qu.empty();
    }
};
void inc(SafeQueue<int>& sq){
    for(int i=0;i<10;i++)
        continue;
    if(sq.isEmpty())
        sq.push(1);
}
void inc1(SafeQueue<int>& sq){
    for(int i=0;i<10;i++)
        continue;
    if(sq.isEmpty())
        sq.push(2);
}

int main(){
    queue<int>qu;
    SafeQueue<int> sq(qu);
    thread t1(inc,ref(sq));
    thread t2(inc1,ref(sq));
    t1.join();
    t2.join();
    cout<<sq.qu.front();
}

A thread Safe queue is supposed to output 1 at the end,but the output is random either 1 or 2 that means it is not thread safe.Why is this particular program not working?


Solution

  • It doesn't mean the program isn't thread safe. It doesn't mean it's ill-defined and can crash.

    It just means your program's logic is not written to add the items to the queue in any particular order.

    If you want those two items to be added in a specific order, push both from one thread.

    Thread safety doesn't mean your application runs as if it only had one thread.

    Your program is working fine.