Sumit
Sumit

Reputation: 1525

Does std::condition_variable really unlock the given unique_lock object before blocking?

As the reference says: 1) Atomically unlocks lock, blocks the current executing thread, and...

I have below code:

#include <iostream>
#include <thread>
#include <condition_variable>

std::mutex mutex_;
std::condition_variable condVar;
std::unique_lock<std::mutex> lck(mutex_); //purposely global to check return of owns_lock() in main

void waitingForWork()
{
    std::cout << "Before wait, lck.owns_lock() = " << lck.owns_lock() << '\n';

    condVar.wait(lck);

    std::cout << "After wait, lck.owns_lock() = " << lck.owns_lock() << '\n';
}

int main()
{
  std::thread t1(waitingForWork);

  std::this_thread::sleep_for(std::chrono::seconds(10));

  std::cout << "In main, lck.owns_lock() = " << lck.owns_lock() << '\n';
  condVar.notify_one();

  t1.join();
  return 0;
}

Compiled using: g++ with c++17 on ubuntu

The output:

Before wait, lck.owns_lock() = 1
In main, lck.owns_lock() = 1
After wait, lck.owns_lock() = 1

But as per reference, I expected the mutex to get unlocked upon wait, i.e.:

In main, lck.owns_lock() = 0

Could someone please tell me why is it so ?

Upvotes: 1

Views: 110

Answers (1)

mpoeter
mpoeter

Reputation: 3001

You have to read further:

When unblocked, regardless of the reason, lock is reacquired and wait exits. If this function exits via exception, lock is also reacquired.

So it is always guaranteed that upon exit of wait, the lock is reacquired.

Upvotes: 2

Related Questions