v0ldem0rt
08/13/2018, 5:13 PMMartin Devillers
08/13/2018, 5:16 PMv0ldem0rt
08/13/2018, 5:18 PMelizarov
08/13/2018, 5:18 PMv0ldem0rt
08/13/2018, 5:18 PMelizarov
08/13/2018, 5:18 PMv0ldem0rt
08/13/2018, 5:20 PMelizarov
08/13/2018, 5:20 PMN
coroutines reading tasks from the same channel and performing them. Thus you’ve limited concurrent to N
concurrent coroutines without having to use a semaphore.v0ldem0rt
08/13/2018, 5:49 PMimport kotlinx.coroutines.experimental.channels.Channel
import kotlinx.coroutines.experimental.channels.count
import kotlinx.coroutines.experimental.runBlocking
import kotlinx.coroutines.experimental.timeunit.TimeUnit
import kotlinx.coroutines.experimental.withTimeoutOrNull
class SuspendSemaphore(initialCount: Int) {
private val channel = Channel<Unit>()
init {
runBlocking {
repeat(initialCount) { channel.send(Unit) }
}
}
val onAcquire get() = channel.onReceive
suspend fun getCurrentCounter() = channel.count()
suspend fun acquire() = channel.receive()
suspend fun release() = channel.send(Unit)
suspend fun tryAcquire(timeout: Long = 0, timeUnit: TimeUnit = TimeUnit.MILLISECONDS): Boolean {
return withTimeoutOrNull(timeout, timeUnit) {
channel.receive()
} == Unit
}
}
Let me know if anything sounds suspeciouselizarov
08/13/2018, 5:54 PMlouiscad
08/13/2018, 8:36 PMinitialCount
into Channel<Unit>(…)
call, and use offer(Unit)
without runBlocking { … }
? Your code seems deadlocking to me.v0ldem0rt
08/13/2018, 8:47 PM