Is there an equivalent to C#'s Semaphore/SemaphoreSlim type, in Kotlin? I would like to use it with co-routines (non-blocking). I.e. WaitOneAsync().
kotlinx-coroutines
now has a full-fledged Semaphore
class.
You can use it as follows:
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
suspend fun doConcurrently(list: List<Something>) {
val semaphore = Semaphore(4) // number of permits is 4
list
.map { async { semaphore.withPermit { /* do something */ } } }
.awaitAll()
}
You have a few options coming from Java.
Most common would be to use CountDownLatch
:
val latch = CountDownLatch(1)
async {
// Do something
latch.countDown()
}
latch.await()
Usually that's enough.
If you have some very specific cases, you can also use semaphore, of course:
launch {
try {
semaphore.acquire()
// Do something
}
finally {
semaphore.release()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With