acquire method
Waits for a permit, then acquires it. Completes immediately when a permit is free, otherwise queues until release hands one over. Audited: 2026-06-12 11:26 EDT
Implementation
Future<void> acquire() async {
if (_available > 0) {
_available--;
return;
}
final Completer<void> c = Completer<void>();
_waiters.add(c.complete);
// The woken waiter does NOT decrement `_available`: [release] transfers the
// permit DIRECTLY to it (without incrementing), so the permit count is
// already correct. Decrementing here would double-count and, combined with
// an increment in release, let a fast-path acquirer steal the permit in the
// wake-up gap — admitting two holders and driving the count negative.
await c.future;
}