Skip to content

Instantly share code, notes, and snippets.

@bradynpoulsen
Created February 12, 2019 15:12
Show Gist options
  • Save bradynpoulsen/bcae3addb19de57ecba854df20623f3e to your computer and use it in GitHub Desktop.
Save bradynpoulsen/bcae3addb19de57ecba854df20623f3e to your computer and use it in GitHub Desktop.
Mutex pool that can be used to limit the number of workers operating at the same time
import kotlinx.coroutines.selects.select
import kotlinx.coroutines.sync.Mutex
class MutexPool(val pool: Set<Mutex>) {
constructor(poolSize: Int) : this((1..poolSize).map { Mutex() }.toSet())
suspend inline fun <R> withLock(crossinline block: () -> R): R = select {
pool.forEach {
it.onLock { lockedMutex ->
try {
block()
} finally {
lockedMutex.unlock()
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment