]> git.ipfire.org Git - thirdparty/gcc.git/commit
libstdc++: Ensure counting_semaphore::try_acquire_for times out [PR122878]
authorJonathan Wakely <jwakely@redhat.com>
Fri, 9 Jan 2026 15:29:13 +0000 (15:29 +0000)
committerJonathan Wakely <redi@gcc.gnu.org>
Fri, 9 Jan 2026 19:18:21 +0000 (19:18 +0000)
commit9eb863f1523c49aa4860ce2a4d0d8bd181ef20fb
treeb08000d13b9ccadaa77dd9cad0be593821924817
parentb405a04ffde07e9a3021b74a5d40c7938984b88f
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 <tkaminsk@redhat.com>
libstdc++-v3/include/bits/semaphore_base.h