Nick
05/09/2024, 8:16 PMval semaphore = Semaphore(10)
suspend fun Semaphore.use(action: suspend () -> Unit) {
acquire()
try { action() }
finally { release() }
}
suspend fun useExample() {
semaphore.use {
delay(2.seconds)
println("Did a thing")
}
}
suspend fun CoroutineScope.withSemaphore(semaphore: Semaphore, action: suspend () -> Unit) {
semaphore.acquire()
try { action() }
finally { semaphore.release() }
}
suspend fun withSemaphoreExample() = coroutineScope {
withSemaphore(semaphore) {
delay(2.seconds)
println("Doing a thing")
}
}
The normal way of
semaphore.acquire()
try {
// code
} finally {
semaphore.release()
}
can get pretty ugly, especially if it's used liberallykevin.cianfarini
05/09/2024, 8:19 PMuse
function does differently than Semaphore.withPermit
? https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/common/src/sync/Semaphore.kt#L77kevin.cianfarini
05/09/2024, 8:21 PMCoroutineScope.withSemaphore
never uses the receiver CoroutineScope. What does that function do differently than your first use
function?Nick
05/09/2024, 8:23 PM.use
is literally .withPermit
darkmoon_uk
10/01/2024, 3:39 AM