Kotlin Coroutines - Thread Switching
我是Android Coroutines的新手。我一直在阅读官方文档中的内容,并发现了此说明
Important: Using a dispatcher that uses a thread pool like
Dispatchers.IO or Dispatchers.Default does not guarantee that the
block executes on the same thread from top to bottom. In some
situations, Kotlin coroutines might move execution to another thread
after a suspend-and-resume. This means thread-local variables might
not point to the same value for the entire withContext() block.
但是我没听懂这句话
This means thread-local variables might
not point to the same value for the entire withContext() block
有人可以给我展示这种情况的示例吗?
因此,想象一下这种情况:
-
您在
Dispatchers.Default 上launch() 一个协程 -
在该协程中,您
prepare() 一个Looper 并尝试将其用于某些用途(例如,使用Messenger ) -
然后,您调用一些
suspend 函数
当该
这里真正的教训是:使用
这是指对线程静态的变量(请参阅此以供参考)。
这很可能与您无关,线程局部变量的用法非常特定。在正常情况下,协程在恢复后可能会跳到另一个线程这一事实将不会产生任何影响。