0

When I read the book "C++ in concurrent",I see the code about return the std::move(unique_lock<>), for example:

    std::unique_lock<std::mutex> wait_for_data()
    {
        std::unique_lock<std::mutex> head_lock(head_mutex);
        data_cond.wait(head_lock,[&]{return head!=get_tail();});
        return std::move(head_lock);
    }

    std::unique_ptr<node> do()
    {
        std::unique_lock<std::mutex> head_lock(wait_for_data());
        return pop_head();
    }

Are there two locks and two unlocks? Is it same with next example which just have one lock and unlock ? What's the meaning about return the unique_lock<>?

    std::unique_ptr<node> do()
    {
        std::unique_lock<std::mutex> head_lock(head_mutex);
        data_cond.wait(head_lock,[&]{return head!=get_tail();});
        return pop_head();
    }

Thanks in advance for any help!!

ppka
  • 11
  • There is one lock object, created in `wait_for_data`, and passed back out to `do`. It will be locked in `wait_for_data`, and unlocked when `do` exits. (It might be unlocked and relocked in the `wait` call.) – Tim Roberts Mar 20 '23 at 03:29
  • @Tim Roberts, So the lock object leaves `wait_for_data` would not be unlock and passed to function `do` ? – ppka Mar 20 '23 at 11:37
  • No. By using `std::move`, it leaves the state of the mutex unchanged. Ownership just passes to the caller. – Tim Roberts Mar 20 '23 at 17:14

1 Answers1

0

In wait_for_data() unique_lock constructed from mutex (head_mutex). Then in do() unique_lock constructed from unique_lock rvalue that wait_for_data() returned. So in do() you actually use the same unique_lock that wait_for_data() created.

user10
  • 266
  • 5