Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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?

like image 411
q0987 Avatar asked Feb 12 '23 15:02

q0987


1 Answers

Is it because we should release the lock first before calling notify_one() otherwise the lock is hold while we calling the notify_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.

like image 65
Bill Lynch Avatar answered Feb 16 '23 04:02

Bill Lynch