Skip to content

Fix issue 1422, where aquiredPermits param is totally ignored #1423

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion kotlinx-coroutines-core/common/src/sync/Semaphore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ private class SemaphoreImpl(
* and the maximum number of waiting acquirers cannot be greater than 2^31 in any
* real application.
*/
private val _availablePermits = atomic(permits)
private val _availablePermits = atomic(permits - acquiredPermits)
override val availablePermits: Int get() = max(_availablePermits.value, 0)

// The queue of waiting acquirers is essentially an infinite array based on `SegmentQueue`;
Expand Down
12 changes: 12 additions & 0 deletions kotlinx-coroutines-core/common/test/sync/SemaphoreTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -140,4 +140,16 @@ class SemaphoreTest : TestBase() {
job1.cancel()
finish(6)
}

@Test
fun testAcquiredPermits() = runTest {
val semaphore = Semaphore(5, acquiredPermits = 4)
assertEquals(semaphore.availablePermits, 1)
semaphore.acquire()
assertEquals(semaphore.availablePermits, 0)
assertFalse(semaphore.tryAcquire())
semaphore.release()
assertEquals(semaphore.availablePermits, 1)
assertTrue(semaphore.tryAcquire())
}
}