in kotlinx-coroutines-core/common/src/sync/Semaphore.kt [242:262]
fun release() {
while (true) {
// Increment the number of available permits.
val p = _availablePermits.getAndIncrement()
// Is this `release` call correct and does not
// exceed the maximal number of permits?
if (p >= permits) {
// Revert the number of available permits
// back to the correct one and fail with error.
coerceAvailablePermitsAtMaximum()
error("The number of released permits cannot be greater than $permits")
}
// Is there a waiter that should be resumed?
if (p >= 0) return
// Try to resume the first waiter, and
// restart the operation if either this
// first waiter is cancelled or
// due to `SYNC` resumption mode.
if (tryResumeNextFromQueue()) return
}
}