Coroutine可以悬挂然后在其他线程上恢复吗?第一个线程的内存效果是否传递到第二个线程?

发布于 2025-02-12 11:17:15 字数 359 浏览 0 评论 0原文

考虑

fun main(args: Array<String>) {
    runBlocking {
        launch(Dispatchers.Default) {
            var a = 0
            a++
            delay(100)
            println(a)
        }
    }
}

到调度程序具有多个线程,该程序是否有可能在悬挂delay> delay函数上更改线程?是否保证它将打印“ 1”或a需要atomicInteger

Consider

fun main(args: Array<String>) {
    runBlocking {
        launch(Dispatchers.Default) {
            var a = 0
            a++
            delay(100)
            println(a)
        }
    }
}

Since the Dispatcher has multiple threads, is it possible for the program to change threads at the suspending delay function? Is it guaranteed that it will print '1' or does a need to be AtomicInteger?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

那伤。 2025-02-19 11:17:15

执行暂停delay()函数后,Coroutine可能会继续在dispatchers.default.default线程池的另一个线程上执行。

对于a变量的附加同步不需要,因为它仅在一个coroutine中使用,因此在coroutine内部的代码顺序执行,如果是在保证之前。如果在几个coroutine中使用该变量,则需要比其他同步。

After execution of the suspend delay() function there is a possibility that the coroutine will continue execution on another thread from the Dispatchers.Default thread pool.

There is no need in additional synchronization for a variable, because it is being used only within one coroutine, code within a coroutine executes sequentially, providing happens-before guarantees. If the variable was used within a couple of coroutine than additional synchronization would be needed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文