I have a simple multi threaded program where one thread is filling the queue, while the other is consuming the queue, I know this example program is buggy, which is closely trying to replicate my application. I don't have an explanation as to why it's behaving this way, I expect the output to be popping 1 , 2 , etc
#include <iostream>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
using namespace std;
class A{
public :
int y;
A(int z):y(z){
cout << "constructed =" << y << std::endl;
}
~A(){
cout << "destructed =" << y << std::endl;
}
};
std::mutex lk;
std::queue<shared_ptr<A>> p;
std::condition_variable cv;
int ct = 1;
void waitfordata(){
std::unique_lock<std::mutex> lock(lk);
cv.wait(lock, []{return p.size();});
cout << "popping = " << p.front()->y << endl;
p.pop();
}
void threadhandler(){
while(1){
waitfordata();
}
}
int main()
{
std::thread foo(threadhandler);
std::shared_ptr<A> svc_resp = std::make_shared<A>(ct++);
while(1){
{
std::lock_guard<std::mutex> lock(lk);
p.push(svc_resp);
}
cv.notify_one();
std::this_thread::sleep_for(std::chrono::seconds(1));
std::shared_ptr<A> svc_resp = std::make_shared<A>(ct++);
}
return 0;
}
Ouput which I got
constructed =1
popping = 1
constructed =2
destructed =2
popping = 1
constructed =3
destructed =3
popping = 1
constructed =4
destructed =4
popping = 1
Ouput which I was expecting
constructed =1
destructed =1 <===== why is 1 not destructed
popping = 1
constructed =2
destructed =2
popping = 2 <===== why is this not taking the next data
constructed =3
destructed =3
popping = 3 <===== why is this not taking the next data
constructed =4
destructed =4
popping = 4 <===== why is this not taking the next data
Aucun commentaire:
Enregistrer un commentaire