Visibility in Kotlin coroutines

Man*_*iai 3 concurrency multithreading kotlin kotlin-coroutines

I decided to dive in into Kotlin coroutines. I have some questions regarding visibility. I understand that in absence of a ContinuationInterceptor, it is possible different sections of the same coroutines to be executed by different threads.

How is guaranteed that, after a suspension, the new thread has the correct visibility of the coroutine internal state ?

For example:

    suspend fun doPost(customRatings : Map<String, Int>) : Int {...}

    fun postRatings_1() {
        GlobalScope.launch {
            val mutableMap : MutableMap<String, Int> = mutableMapOf()

            mutableMap["Apple"] = 1
            mutableMap["Banana"] = 2

            // ...

            val postId = doPost(mutableMap)

            // How am I guaranteed to see the two entries here ?
            println("posted ${mutableMap} with id ${postId}") 
        }
    }
Run Code Online (Sandbox Code Playgroud)

Similarly when a new coroutine is launched

    fun postRatings_2() {

        val mutableMap : MutableMap<String, Int> = mutableMapOf()

        mutableMap["Apple"] = 1
        mutableMap["Banana"] = 2


        GlobalScope.launch {
            // How am I guaranteed to see the two entries here ?
            val postId = doPost(mutableMap)
            //...
        }
Run Code Online (Sandbox Code Playgroud)

In both of these cases there is some mutable state shared between two (existing) threads.

I am looking for the "Happens-before" rule that guarantees that the mutable state will be properly visible by the two threads.

Mar*_*nik 5

我正在寻找“先发生”规则,该规则保证可变状态将被两个线程正确可见。

保证很容易实现:例如,如果您的调度程序基于Java线程池,则线程池本身已经提供了此保证。前面的代码executor.submit()调用的之前发生的提交的代码和代码,反过来,之前发生一个遵守相关的未来完成的代码。

即使您使用称为的null-dispatcher,Dispatchers.Unconfined它只是在碰巧要调用的线程上恢复协程continuation.resume(result),您仍然会发生-之前发生,因为调用回调的基础框架保证了它。

您必须编写一个自定义损坏的Dispatcher实现以弄乱顺序,要走得很远。