C++ Logo


Advanced search

Re: [std-proposals] unique_lock<atomic_flag>

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Wed, 22 Feb 2023 20:29:27 -0500
On Wed, Feb 22, 2023 at 7:21 PM Frederick Virchanza Gotham via
Std-Proposals <std-proposals_at_[hidden]> wrote:
> On Wed, Feb 22, 2023, Jason McKesson wrote:
> >
> > You replace your `atomic_flag` with a `binary_semaphore`, and replace
> > your `while` loop with `acquire()` in the constructor, and have the
> > destructor do a `release()`.
> Yeah that's what I was thinking. I might go through my projects and
> replace the atomic_flag's with binary semaphores.
> But anyway I still think you should be able to acquire and release a
> semaphore using 'lock_guard' or 'unique_lock', like this:

No, you shouldn't.

A Lockable type has a built-in assumption: if your thread locks it,
only your thread can unlike it. This allows a scoped lock type like
`unique_lock` to offer the guarantee that if your thread's stack holds
that lock, then only the termination of that scope can unlock it.

A binary_semaphore offers *no such guarantee*. If you can access a
binary_semaphore object, you can *unlock it*. Even if some other
thread locked it, you can unlock it for them. It's not a mutex. In
fact, not being a mutex is the *point of the type*.

This is also why `atomic`s are not, and should not be, Lockable. They
don't participate in the fundamental assumption of ownership of locks.

Received on 2023-02-23 01:30:21