1

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?

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
  • 1
    No. By the way, there are _atomic_ operations for _std::shared_ptr_, see http://en.cppreference.com/w/cpp/memory/shared_ptr/atomic. – nosid Mar 23 '14 at 12:29
  • @nosid: That's an answer, by the way :) – Matthieu M. Mar 23 '14 at 12:31
  • @nosid, thanks for the link -- I'll try that again. I seem to recall that last time I checked, gcc didn't support them properly. And yes, I'd accept that as an answer :) – Drew Noakes Mar 23 '14 at 12:32

1 Answers1

3

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.

nosid
  • 48,932
  • 13
  • 112
  • 139
  • Isn't copying a `shared_ptr` thread-safe? http://stackoverflow.com/q/14482830/420683 – dyp Mar 23 '14 at 13:24
  • @dyp: Yes, copying (i.e. reading) a `std::shared_ptr` is thread-safe, as long as no other thread writes to the same `std::shared_ptr`. – nosid Mar 23 '14 at 13:28
  • Ah ok. So you're protecting with the mutex or using atomic operations against a *write* to that particular `std::shared_ptr` object. – dyp Mar 23 '14 at 13:32