C++ Logo

std-discussion

Advanced search

Re: Synchronization of atomic notify and wait

From: Ryan Nicholl <exaeta_at_[hidden]>
Date: Mon, 25 Jul 2022 13:39:11 +0000
Looking into this closer, looks like I was wrong, wait does come with std::memory_order, which defaults to seq_cst. Notify does not have a memory order but it doesn't need one since notify just triggers a wakeup, but wait must return to sleep if the value is not changed.

Sleep+check of wait is a single atomic operation from the perspective of C++ so it cannot race by itself, it's one operation. If notify can be reordered above the write then that could pose a problem as the notify could be missed and write could happen during a sleep state. Then you may have livelock as I'm pretty sure all implementations will wake eventually. I think the implied behavior of notify is acq_rel signal fence style but notify should get a memory order explicitly for compilers to know not to reorder stuff around notify. Theoretically it sounds possible to do so now? Unless notify is part of the atomic modification order without an associated memory ordering, which could make sense. If notify counts as a modification then there is no race but the link is a bit tenuous.

--
Ryan Nicholl
(678)-358-7765
Sent from Proton Mail mobile
-------- Original Message --------
On Jul 25, 2022, 05:43, Marcin Jaczewski wrote:
> pon., 25 lip 2022 o 06:37 Ryan Nicholl  napisaƂ(a): > > Wait must observe the state changing from expected to something else to return. It cannot deadlock because the sleep is combined with the check through special system calls like SYS_futex. Kernel either A. guarantees you are able to receive notifications on the wait list THEN checks the value for any changes, or B. does both steps of A in an atomic manner, such that no race is possible. One problem i do see is that Linux cannot implement wait correctly on 64 bit values without futex waitv which is a pretty recent add-on, but I think libatomic authors will find a workaround (I assume), though it might be slightly slower, such as a global lock? > > How its implemented does not matter, it could be that non current real machine could have this problem. But this is still a problem in standard as on its own it is still broken or more accurately not precise enough. I could implement C++ Abstract Machine simulator, and follow the standard to the letter, and it could misbehave and deadlock. There will not be any system calls or cache levels but I still have 100% of what C++ can do. Another thing is sanitizers, how do they know what code is UB and what is correct if the standard does not say it? Most of the bugs found by them could "work fine" on the current CPU.

Received on 2022-07-25 13:39:21