I've been doing a fair bit of work with semaphores...
# coroutines
n
I've been doing a fair bit of work with semaphores lately and I've been thinking one of these two (or both) should be part of the std lib, what do you all think?
Copy code
val semaphore = Semaphore(10)

suspend fun Semaphore.use(action: suspend () -> Unit) {
  acquire()
  try { action() }
  finally { release() }
}

suspend fun useExample() {
  semaphore.use {
    delay(2.seconds)
    println("Did a thing")
  }
}

suspend fun CoroutineScope.withSemaphore(semaphore: Semaphore, action: suspend () -> Unit) {
  semaphore.acquire()
  try { action() }
  finally { semaphore.release() }
}

suspend fun withSemaphoreExample() = coroutineScope {
  withSemaphore(semaphore) {
    delay(2.seconds)
    println("Doing a thing")
  }
}
The normal way of
Copy code
semaphore.acquire()
try {
  // code
} finally {
  semaphore.release()
}
can get pretty ugly, especially if it's used liberally
1
k
Is there something that your
use
function does differently than
Semaphore.withPermit
? https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/common/src/sync/Semaphore.kt#L77
💡 1
Also, your function
CoroutineScope.withSemaphore
never uses the receiver CoroutineScope. What does that function do differently than your first
use
function?
n
oh wow, I did some brief searching but I didn't know there was already a solution to this. the answer is nothing.
.use
is literally
.withPermit
👍 2
d
Nice resolution - in these scenarios I normally like to place an '_EDIT: ..._' in the original post to highlight the solution, as an FYI for folk who don't enter the thread.