kotlinkotlinx.coroutines

Equivalent to C#'s Semaphore/SemaphoreSlim in Kotlin?


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().


Solution

  • 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()
    }