c++ - why we should put `std::unique_lock` under a local scope? -



c++ - why we should put `std::unique_lock` under a local scope? -

based on c++ equivalent 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) { // question //{ // comment out scope std::unique_lock<std::mutex> lock(this->d_mutex); d_queue.push_front(value); //} // comment out scope this->d_condition.notify_one(); }

question: why should introduce local scope {} cover std::unique_lock within put function? because should release lock first before calling notify_one otherwise lock hold while calling notify_one?

t pop() { std::unique_lock<std::mutex> lock(this->d_mutex); this->d_condition.wait(lock, [=]{ homecoming !this->d_queue.empty(); }); t rc(std::move(this->d_queue.back())); this->d_queue.pop_back(); homecoming rc; }

question: why should utilize [=] within pop function?

is because should release lock first before calling notify_one() otherwise lock hold while calling notify_one()?

correct. it's possible other thread spins , attempts grab queue's lock before producer thread has released it. cause wake (because of status variable), , go sleep (because of lock).

why should utilize [=] within pop function?

we accessing this. lambda needs access d_queue through method, , chose copying this value.

c++ c++11

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -