Mutex is there but I need the permits logic of sem...
# coroutines
m
Mutex is there but I need the permits logic of semaphores
g
Could you show some example of code where you need it
Probably this thread also may be interesting for you https://kotlinlang.slack.com/archives/C1CFAFJSK/p1549980138040900
m
use case is a count latch
g
CountDownLatch is mostly not needed for coroutines
m
so it's exactly a channel, multiple possible producers, one consumer that waits for jobs to close resource
g
could you show some self contained example, probably there is better solution for coroutines
m
it's classic reader writer problem
g
also related topic about CountDownLatch in coroutines https://github.com/Kotlin/kotlinx.coroutines/issues/59
m
so it's quite easy to implement with something that can count active writers, in Java that would be quick to implement with semaphores
or a count latch
I have my own mini wrapper to create a suspending semaphore, it's really just a wrapped channel
wanted to know if there is something already done in kotlin coroutines library with same functionality
g
I would like to see your current implementation, hard to say without example
m
oh well, thanks for the link, looks like I actually need a Phaser
didn't know about that structure
fits exactly
Copy code
class SuspendSemaphore(permits: Int = 0,
                                capacity: Int = Channel.UNLIMITED) {

    private val channel = Channel<Unit>(capacity)

    init {
        repeat(permits) {
            channel.offer(Unit)
        }
    }

    suspend fun acquire() {
        channel.receive()
    }

    fun release() {
        channel.offer(Unit)
    }
}
👍 2
sure, it's super simple to implement a semaphore with a channel
c
It might be nice to have this in kotlinx.coroutines.
j
It might be nice to have this in kotlinx.coroutines.
As @gildor said, it is not needed with coroutines. (more explanation by @elizarov in https://github.com/Kotlin/kotlinx.coroutines/issues/59).
A read-write mutex may be added in kotlinx.coroutines though: https://github.com/Kotlin/kotlinx.coroutines/pull/408