Boost logo

Boost :

From: Howard Hinnant (hinnant_at_[hidden])
Date: 2007-08-22 10:10:54

On Aug 22, 2007, at 9:43 AM, David Abrahams wrote:

> on Mon Aug 20 2007, Howard Hinnant <>
> wrote:
>> Here is a link to a reference implementation and a FAQ for mutexes,
>> locks and condition variables I am currently anticipating proposing
>> for C++ standardization (or subsequent TR).
> I find the fact that unique_lock can reference a mutex without owning
> the mutex's lock rather confusing in light of the semantics of
> unique_ptr. It seems like unique_lock is looking more like the
> old-old auto_ptr.

The analogy with smart pointers isn't exact. This is no different
than the current boost scoped_lock:

boost::mutex mut;
boost::mutex::scoped_lock lk(mut);

// lk now references mut but does not own the lock on it.

> And what does it mean to construct a unique_lock from a shared_lock?
> How many owners are there if I copy a shared lock and construct a
> unique_lock from the copy? Fundamentally I want to know what is
> really "unique" about unique_lock.

shared_locks aren't copyable. They are move-only.

In order to construct a unique_lock from a shared_lock the referenced
mutex must support:

    bool try_unlock_shared_and_lock();
    template <class elapsed_time>
       bool timed_unlock_shared_and_lock(const elapsed_time& rel_time);

The syntax is:

std::upgrade_mutex mut;
std::shared_lock<std::upgrade_mutex> sl(mut);
std::unique_lock<std::upgrade_mutex> ul(std::move(sl),

The unique_lock constructor will try to convert the ownership of the
mutex from shared to unique (exclusive). It will fail if there is
more than one shared lock on the mutex. If it is successful, then
"ul" will own the exclusive lock state of "mut", and no one will own a
shared lock on the mut. If it fails, "sl" will continue to own a
shared lock on mut.

For a variable "ul" of type unique_lock<Mutex>, if ul.owns() returns
true, then "ul" is the one and only owner of the exclusive lock state
on the mutex of type Mutex pointed to by ul.mutex().


Boost list run by bdawes at, gregod at, cpdaniel at, john at