https://gcc.gnu.org/bugzilla/show_bug.cgi?id=122878
--- Comment #6 from GCC Commits <cvs-commit at gcc dot gnu.org> --- The master branch has been updated by Jonathan Wakely <[email protected]>: https://gcc.gnu.org/g:9eb863f1523c49aa4860ce2a4d0d8bd181ef20fb commit r16-6657-g9eb863f1523c49aa4860ce2a4d0d8bd181ef20fb Author: Jonathan Wakely <[email protected]> Date: Fri Jan 9 15:29:13 2026 +0000 libstdc++: Ensure counting_semaphore::try_acquire_for times out [PR122878] As noted in Bug 122878 comment 2, the _M_try_acquire_for implementation doesn't reduce the remaining timeout each time it returns from an atomic waiting function. This means that it can wait longer than requested, or even loop forever. If there is a spurious wake from the timed waiting function (__wait_until_impl) it will return indicating no timeout occurred, which means the caller will check the value and potentially sleep again. If spurious wakes happen every time, it will just keep sleeping in a loop forever. This is observed to actually happen on FreeBSD 14.0-STABLE where pthread_cond_timedwait gets a spurious wake and so never times out. The solution in this commit is to replace the implementation of _M_try_acquire_for with a call to _M_try_acquire_until, converting the relative timeout to an absolute timeout against the steady clock. This is what ends up happening anyway, because we only have a __wait_until_impl entry point into the library internals, so __atomic_wait_address_for already converts the relative timeout to an absolute timeout (except for the special case of a zero-value duration, which only checks for an update while spinning for a finite number of iterations, and doesn't sleep). As noted in comment 4 of the PR, this requires some changes to _M_try_acquire which was relying on the behaviour of _M_try_acquire_for for zero-value durations. That behaviour is desirable for _M_try_acquire so that it can handle short-lived contention without failing immediately. To preserve that behaviour of _M_try_acquire it is changed to do its own loop and to call __atomic_wait_address_for directly with a zero duration, to do the spinloop. libstdc++-v3/ChangeLog: PR libstdc++/122878 * include/bits/semaphore_base.h (_M_try_acquire): Replace _M_try_acquire_for call with explicit loop and call to __atomic_wait_address_for. (_M_try_acquire_for): Replace loop with call to _M_try_acquire_until. Co-authored-by: Tomasz KamiÅski <[email protected]>
