Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 227
HelloWorld Avatar asked Oct 16 '25 07:10

HelloWorld


2 Answers

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()
}
like image 122
Kirill Rakhman Avatar answered Oct 18 '25 07:10

Kirill Rakhman


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()
    }
}
like image 33
Alexey Soshin Avatar answered Oct 18 '25 06:10

Alexey Soshin