I want to solve the multiple producer single consumer problem and, the following code shows one producer and one consumer thread in an infinite while loop, (I did this to test my code) but it gives wrong data output and then a segmentation fault after some time this is the code i tried:
#include<iostream>
#include<mutex>
#include<condition_variable>
#include<malloc.h>
#include<unistd.h>
#include<thread>
#include<assert.h>
#define QUEUE_SIZE 100
using namespace std;
struct node
{
int data;
};
template<class T, unsigned long Q_SIZE = QUEUE_SIZE>
class NaiveQueue {
private:
static const unsigned long Q_MASK = Q_SIZE - 1;
unsigned long head_, tail_;
std::condition_variable cond_empty_;
std::condition_variable cond_overflow_;
std::mutex mtx_;
T **ptr_array_;
public:
NaiveQueue(): head_(0), tail_(0)
{
ptr_array_ = (T **)::memalign(getpagesize(),Q_SIZE * sizeof(void *));
assert(ptr_array_);
}
void push(T *x)
{
std::unique_lock<std::mutex> lock(mtx_);
cond_overflow_.wait(lock, [this]() {
return tail_ + Q_SIZE > head_;
});
ptr_array_[head_++ & Q_MASK] = x;
cond_empty_.notify_one();
}
T* pop()
{
std::unique_lock<std::mutex> lock(mtx_);
cond_empty_.wait(lock, [this]() {
return tail_ < head_;
});
T *x = ptr_array_[tail_++ & Q_MASK];
cond_overflow_.notify_one();
return x;
}
};
void producer(NaiveQueue<node> &obj)
{
while(1)
{
node *temp;
temp=new node();
temp->data=10;
obj.push(temp);
cout<<"\nPushed : "<<10;
}
}
void consumer(NaiveQueue<node> &obj)
{
while(1)
{
node *temp;
temp=NULL;
temp=obj.pop();
if(temp)
{
cout<<"\nRemoved : "<<temp->data;
delete temp;
}
}
}
int main()
{
NaiveQueue<node> obj;
thread t1(producer,ref(obj));
thread c1(consumer,ref(obj));
t1.join();
c1.join();
return 0;
}
Produces this output:
Pushed :
Removed : 1010
Pushed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Removed : 10
Removed : 10
Removed : 10
Removed : 10
Removed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Pushed :
Removed : 1010
Pushed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Removed : 10
Removed : 10
Removed : 10
Removed : 10
Removed : 10
Removed : -1140848048
Removed : -1140847792
Removed : -1140847760
Removed : -1140847856
Removed : -1140847824
Removed : -1140847792
Removed : -1140847760
Removed : -1140847856
Removed : -1140847824
Removed : -1140847792
Removed : -1140847760
Removed : -1140847856
Removed : -1140847824
Removed : -1140847792
Removed : -1140847760
Removed : -1140847856
Removed : -1140847824
Removed : -1140847792
Pushed : 10
Pushed :
Removed : 1010
Pushed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Pushed : 10
Segmentation fault
Where did I go wrong? Why is -1140847856
being removed when it wasn't pushsed at the first place.