0

Is this:

std::mutex mutex;
for () {
    std::unique_lock<mutex> lock(mutex);
    // do something
    lock.unlock();
}

Equivalent to this in terms of releasing and acquiring the lock every iteration of the for loop?

std::mutex mutex;
for () {
    std::unique_lock<mutex> lock(mutex);
    // do something
}

Related questions:

  1. Is using unique_lock in new scope equivalent to unlock call at the end of work with shared resource?
  2. boost scoped_lock on mutex in while(1) loop
  3. Creating new pointer object in loop
  4. Reusing a unique_lock in a consumer loop
Evandro Coan
  • 8,560
  • 11
  • 83
  • 144
  • 5
    `std::unique_lock`'s constructor acquires the lock, and its destructor unlocks it. This is a core principle of RAII style programming. So yes, these two are codes are equivalent. You don't need to `unlock()` manually, just let the `lock` go out of scope. – Remy Lebeau May 06 '21 at 18:58
  • 2
    No, it's RAII. It does it for you. (There are very specific cases you should call unlock, but this is not one of them) – JHBonarius May 06 '21 at 18:59
  • 1
    Consider using [scoped_lock](https://en.cppreference.com/w/cpp/thread/scoped_lock) unless you have compelling reasons not to. – SergeyA May 06 '21 at 19:04

0 Answers0