Should a unique_lock be released after being unlocked if it won't be used again during its lifetime?

StackOverflow https://stackoverflow.com/questions/22590886

Question

I am using a std::mutex to copy a std::shared_ptr at the beginning of a function.

// Lock the mutex
unique_lock<mutex> guard(d_mutex);

// Copy a shared_ptr
auto ptr = d_ptr;

// Unlock the mutex
guard.unlock();

// Operate with local ptr copy

During the operation, the guard remains associated with d_mutex.

My question is: is there any reason to release() the guard in addition to unlock()ing it?

Was it helpful?

Solution

The purpose of the member function std::unique_lock::release is to be able to transfer the ownership of the lock to some other place. It is similar to the member function std::unique_ptr::release, which transfers the ownership of the pointer (i.e. the responsibility to free the memory) to some other code.

That means: No, there is no need to release a std::unique_lock after it has been unlocked.

By the way: If you only have to protect concurrent accesses to a std::shared_ptr, then you should take a look at the atomic operations for std::shared_ptr:

These operations are already supported by Clang 3.5, although the implementation is not lock free. GCC 4.8 doesn't support these operations at all.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top