Skip to content

Instantly share code, notes, and snippets.

@pambrose
Last active September 11, 2019 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pambrose/4eb82e623161ee7758551ad6a9649ab6 to your computer and use it in GitHub Desktop.
Save pambrose/4eb82e623161ee7758551ad6a9649ab6 to your computer and use it in GitHub Desktop.
Example of select on mutext.onLock
package org.athenian.select
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.selects.select
import kotlinx.coroutines.sync.Mutex
fun selectOnUnlock() {
// Initialize mutexes as locked
val mutex0 = Mutex(true)
val mutex1 = Mutex(true)
val mutex2 = Mutex(true)
runBlocking() {
launch {
repeat(3) {
val selected =
select<String> {
mutex0.onLock { "mutex0" }
mutex1.onLock { "mutex1" }
mutex2.onLock { "mutex2" }
}
println("Selected: $selected")
}
}
println("Unlocking: mutex2")
mutex2.unlock()
delay(100)
println("Unlocking: mutex1")
mutex1.unlock()
delay(100)
println("Unlocking: mutex0")
mutex0.unlock()
}
}
fun selectOnLock() {
// Initialize mutexes as unlocked
val mutex0 = Mutex(false)
val mutex1 = Mutex(false)
val mutex2 = Mutex(false)
runBlocking() {
launch {
repeat(3) {
val selected =
select<String> {
mutex0.onLock { "mutex0" }
mutex1.onLock { "mutex1" }
mutex2.onLock { "mutex2" }
}
println("Selected: $selected")
}
}
println("Locking: mutex2")
mutex2.lock()
delay(100)
println("Locking: mutex1")
mutex1.lock()
delay(100)
println("Locking: mutex0")
mutex0.lock()
}
}
fun main() {
// I would not expect this to work
println("Calling selectOnUnlock()")
selectOnUnlock()
//I would expect this to work
println("\nCalling selectOnLock()")
selectOnLock()
}
/*
Output is:
Calling selectOnUnlock()
Unlocking: mutex2
Selected: mutex2
Unlocking: mutex1
Selected: mutex1
Unlocking: mutex0
Selected: mutex0
Calling selectOnLock()
Locking: mutex2
Selected: mutex0
Selected: mutex1
Locking: mutex1
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment