关于android:Kotlin协程-线程切换

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

有人可以给我展示这种情况的示例吗?


上的

myLooper()prepare()使用线程局部变量来保存每个线程Looper实例。

因此,想象一下这种情况:

  • 您在Dispatchers.Defaultlaunch()一个协程
  • 在该协程中,您prepare()一个Looper并尝试将其用于某些用途(例如,使用Messenger)
  • 然后,您调用一些suspend函数

当该suspend函数返回时,您可能与调用该suspend函数之前的线程不在同一线程上。这将是来自Dispatchers.Default的线程,但不一定是您之前使用的特定线程。结果,您的Looper可能与其他线程相关联,您正在与协程系统配合使用该线程。根据您在此处尝试执行的操作,您在不同线程上的事实可能会导致您想要Looper的问题。

这里真正的教训是:使用HandlerThread而不是prepare()来获得Looper


这是指对线程静态的变量(请参阅此以供参考)。

这很可能与您无关,线程局部变量的用法非常特定。在正常情况下,协程在恢复后可能会跳到另一个线程这一事实将不会产生任何影响。