I found this code on code review stack exchange which implements a producer-consumer problem. I am posting a section of code here.
In the given code, let's consider a scenario when producer produces a value by calling void add(int num)
, it acquires lock on mutex mu
and buffer.size()==size_
this makes the producer go on wait queue due to the conditional variable cond
.
At the same moment, a context switch takes place and consumer calls function int remove()
to consume value , it tries to acquire the lock on mutex mu
, however the lock has already been acquired previously by the producer so it fails and never consumes the value, hence causing a deadlock.
Where am I going wrong here ? Because the code seems to work properly when I run it, debugging it didn't help me.
Thanks
void add(int num) {
while (true) {
std::unique_lock<std::mutex> locker(mu);
cond.wait(locker, [this](){return buffer_.size() < size_;});
buffer_.push_back(num);
locker.unlock();
cond.notify_all();
return;
}
}
int remove() {
while (true)
{
std::unique_lock<std::mutex> locker(mu);
cond.wait(locker, [this](){return buffer_.size() > 0;});
int back = buffer_.back();
buffer_.pop_back();
locker.unlock();
cond.notify_all();
return back;
}
}
while (true) {..; return;}
... why using loop ? – Dubrovnik