https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

Andrew Gazelka

04/26/2019, 10:44 PM
I have a system where I have multiple `Resource`s where only one process (coroutine) should be able to access it at a time. The main function of a
Resource
is
Copy code
suspend fun take(priority: Int = 0, immediate: Boolean = false)
where a task with a lower priority will be scheduled first and higher later. The
immediate
argument will determine whether the currently executing process should be interrupted if
take(...)
has a lower priority than the currently executing task. A resource is given back with
Resource#giveBack()
. Any recommendations on how I could do this idiomatically?
d

Dominaezzz

04/26/2019, 11:42 PM
About interruptions, what happens to the coroutine? Does it have to call
take
again? Does it just "pause" until the new coroutine is done?
a

Andrew Gazelka

04/27/2019, 2:17 AM
@Dominaezzz I thought this over... probably should never interrupt another process
doesn't really make sense
so
Copy code
suspend fun take(priority: Int = 0)
and then if you had some periodic background task you could have something like this
Copy code
while(true){
  resource.take(9999)
  // do things
  resource.giveBack()
  delay(1_000)
}
d

Dominaezzz

04/27/2019, 9:47 AM
For something like this, I'd make a
PriorityMutex
that'll be similar to the
Mutex
class. https://github.com/Kotlin/kotlinx.coroutines/blob/69c26dfbcefc24c66aadc586f9b5129894516bee/kotlinx-coroutines-core/common/src/sync/Mutex.kt but do some insertion sort.
2 Views