Coroutine可以悬挂然后在其他线程上恢复吗?第一个线程的内存效果是否传递到第二个线程?
考虑
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
执行
暂停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 theDispatchers.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.