[libcxx-commits] [libcxx] [libc++] fix `counting_semaphore` lost wakeups (PR #79265)
Jan Kokemüller via libcxx-commits
libcxx-commits at lists.llvm.org
Wed Jan 31 12:36:17 PST 2024
================
@@ -94,20 +95,25 @@ public:
auto __old = __a_.fetch_add(__update, memory_order_release);
_LIBCPP_ASSERT_ARGUMENT_WITHIN_DOMAIN(
__update <= _LIBCPP_SEMAPHORE_MAX - __old, "update is greater than the expected value");
-
- if (__old > 0) {
- // Nothing to do
- } else if (__update > 1)
+ (void)__old;
+ if (__update > 1) {
__a_.notify_all();
- else
+ } else {
__a_.notify_one();
+ }
}
_LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI void acquire() {
auto const __test_fn = [this]() -> bool {
auto __old = __a_.load(memory_order_relaxed);
return (__old != 0) && __a_.compare_exchange_strong(__old, __old - 1, memory_order_acquire, memory_order_relaxed);
};
- __cxx_atomic_wait(&__a_.__a_, __test_fn);
+ auto const __test_with_old = [this](__cxx_contention_t& __monitor) -> bool {
----------------
jiixyj wrote:
> I don't think `latch` has the same problem as the none of the waiters are going to change anything. In fact, I don't understand why `latch` needs to use this complicated internal functions at all. can't it just do
>
> ```
> __a_.wait(0, memory_order_acquire);
> ```
I think it's written in terms of `try_wait()` and `__cxx_atomic_wait` to express the separation of concerns -- the `latch` only has to implement the non-blocking logic in `try_wait()`, and `__cxx_atomic_wait` "generically" turns the `try_wait()` into a blocking algorithm. To do this, `__cxx_atomic_wait` implements the "event count" pattern:
- https://github.com/facebook/folly/blob/dd5e8b4fcef37193cd9676e1122d1621a1d90c49/folly/experimental/EventCount.h
- https://cbloomrants.blogspot.com/2011/07/07-08-11-who-ordered-event-count.html
What complicates the internal `__cxx_atomic_wait` eventcount logic a lot is that sometimes the eventcount futex is from the "parking lot" (i.e. `__libcpp_contention_table`) and other times it is the atomic variable itself if it's directly usable as a platform futex (leading to those ABA style issues).
https://github.com/llvm/llvm-project/pull/79265
More information about the libcxx-commits
mailing list