I am trying to make sure these two methods are synchronized. What I noticed is that Coroutines are harder to synchronize than Threads. How can I guarantee that if I call start()
then stop()
that my code will actually be stopped at the end?
object Test {
private val coroutine = CoroutineScope(Dispatchers.IO)
@Synchronized
fun start() {
coroutine.launch {
// some work
}
}
@Synchronized
fun stop() {
coroutine.launch {
// clean up then stop
}
}
}
My concern is I call start()
then stop()
but actually stop executes first. So my code continues when it should have stopped.
Synchronization or sequential execution of commands are two different things.
If you need execute "start" then "stop", simply do not create new coroutines with your's "coroutine.launch", instead use suspend keyword for your function, then execute them like this :
suspend fun start() {}
suspend fun stop() {}
fun main() {
scope.launch {
start()
stop()
}
}
But if you want to synchonized two method you can read an official Kotlin guide to shared mutable state which presents a few good solutions. And do somethink like this :
val mutex = Mutex()
suspend fun main() {
mutex.withLock {
start()
stop()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With