C++ Logo

std-proposals

Advanced search

Re: [std-proposals] atomic_compare_exchange_and_notify

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Wed, 14 Jan 2026 11:07:59 +0000
On Wed, 14 Jan 2026, 00:55 Ryan P. Nicholl via Std-Proposals, <
std-proposals_at_[hidden]> wrote:

> It has come to my attention that it isn't possible to implement data
> structures like std::latch or a uselock using the C++ atomic library
> without undefined behavior.
>
> Namely, std::latch guarantees that count_down doesn't cause a race even if
> there are waiters, this isn't possible to implement on the abstract machine
> unless the notification can be safely executed atomically with the value
> set. Ordinary notify_one has undefined behavior if it races with the
> destructor of the atomic object.
>

That doesn't mean it isn't possible to implement. It means you have to be
careful how you use it.

Most types don't guarantee that you can destroy them while another thread
is still using them, this isn't specific to std::latch. I think "it isn't
possible to implement" is framing this completely wrong.

It's also not true, you could implement it with a std::mutex and a
std::condition_variable if you want to guarantee that waiters do not wake
before a notify is complete.


> Of course, it's possible to implement std::latch using things like
> SYS_futex, so this isn't impossible to implement per se, only impossible to
> implement using the C++ standard library without relying on undefined
> behavior.
>

It's possible using FUTEX_WAKE_OP, but what about non-linux platforms?


> I would propose adding atomic_compare_exchange_and_notify. This would
> have the same behavior as atomic compare_exchange followed by notify,
> except that it doesn't cause undefined behavior if a waiter unblocks on the
> new value and destroys the atomic, which could race with notify.
>

How would that work for std::atomic<long long> which doesn't use a futex
directly?

I definitely think it would be nice to have a C++ type that exposes futex
functionality directly with no additional overhead, but std::atomic is not
that type.

Received on 2026-01-14 11:08:16