kotlin - 在 withContext 之后切换协程上下文
问题描述
假设我们有io
用于阻塞操作的协程上下文和async
用于非阻塞操作(如协程执行)的协程上下文。如何有效地实施追随?
/**
* Eval [f] on thread pool defined by [on], then continue execution on [continueOn] context
*/
suspend fun <A> eval<A>(f: () -> A, on: CoroutineContext, continueOn: CoroutineContext): A
eval({ readFileBlocking() }, io, async)
eval
可以从任何上下文中调用,包括Unconfined
. withContext(continueOn) { withContext(on) { f() }}
有效但效率低下 - 它强制最多 4 个线程池切换,而最佳值为 2(从输入上下文到阻塞池,然后到结果上下文)
问答
为什么不只是
withContext(IO){ ... }
?如果不受限制的上下文执行将在 IO 线程上继续,这是我要避免的行为
为什么不
withContext(IO){ ... } ; withContext(async){ ... }
呢?如果我们把它放在一个函数中,它也有同样的问题——不受限制的上下文将继续在 IO 线程上执行。如果我们不这样做,我不喜欢
withContext(async)
仅仅因为某处调用了 IO 上下文而到处写的想法。
解决方案
推荐阅读
- python - 对于虚拟 conda 环境,PyCharm 不工作,而 Jupyter notebook 工作
- reactjs - React useState 等待状态被设置
- php - PHP 文件下载:PHP 正在 ajax 响应中发送文件数据,但文件未下载
- javascript - 如何修复 _this.video 未定义
- gis - 从 NetLogo 中的栅格数据分配补丁值
- python-3.x - 有没有办法跟踪函数在 n 秒内被调用的次数?
- raspberry-pi - 未能加载提供程序 SiloedPackageProvider.dll 和 metaDeployProvider.dll
- julia - Julialang:在抽象类型上强制执行接口
- linux - 触发 IRQ 处理程序后如何写入文件?
- java - Cassandra 是否有可能返回不一致的值?