Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to synchronize coroutine?

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.

like image 427
J_Strauton Avatar asked Jan 31 '20 06:01

J_Strauton


1 Answers

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()
    }
}
like image 64
i30mb1 Avatar answered Oct 06 '22 00:10

i30mb1