Created
February 12, 2019 15:12
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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