Based on C++ Equivalent to Java's BlockingQueue
void push(T const& value) { // original version
{
std::unique_lock<std::mutex> lock(this->d_mutex);
d_queue.push_front(value);
}
this->d_condition.notify_one();
}
void push(T const& value) { // my question
//{ // comment out the scope
std::unique_lock<std::mutex> lock(this->d_mutex);
d_queue.push_front(value);
//} // comment out the scope
this->d_condition.notify_one();
}
Question: why we should introduce a local scope {}
to cover the std::unique_lock
inside the put
function? Is it because we should release the lock first before calling notify_one
otherwise the lock is hold while we calling the notify_one
?
T pop() {
std::unique_lock<std::mutex> lock(this->d_mutex);
this->d_condition.wait(lock, [=]{ return !this->d_queue.empty(); });
T rc(std::move(this->d_queue.back()));
this->d_queue.pop_back();
return rc;
}
Question: why we should use [=]
inside the pop
function?
Is it because we should release the lock first before calling
notify_one()
otherwise the lock is hold while we calling thenotify_one()
?
Correct. It's possible that the other thread spins up and attempts to grab the queue's lock before the producer thread has released it. Which would cause it to wake up (because of the condition variable), and then go back to sleep (because of the lock).
why we should use
[=]
inside the pop function?
We are accessing this
. The lambda needs to access d_queue
through some method, and they chose copying this
by value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With