使用分派器IO和默认值之间的差异 [英] Difference between usage of Dispatcher IO and Default

查看:343
本文介绍了使用分派器IO和默认值之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此问题中:科特琳·协程选择Dispatcher 我们可以理解在CPU进程中使用Dispatcher.Default,例如在写入/读取文件或API连接时进行图像/视频转换和Dispatcher.IO.

In this question: Kotlin Coroutines choosing Dispatcher we can understand to use Dispatcher.Default on CPU process, like an image/video conversion and Dispatcher.IO when writing/reading files or API connection.

但是在Dispatcher.kt类文档中,对于IO您会发现:

But in the class Dispatcher.kt documentation, for the IOyou find this:

* This dispatcher shares threads with a [Default][Dispatchers.Default] dispatcher, so using
* `withContext(Dispatchers.IO) { ... }` does not lead to an actual switching to another thread —
* typically execution continues in the same thread.

因此,基本上它们无论如何都在同一线程上运行.有真正的区别,还是最终每个人都用不着?

So basically they run on the same thread anyway. There is a real difference or in the end it won't matter each one to use?

谢谢!

推荐答案

区别在于Dispatchers.Default限于CPU内核数(最少2个),因此仅N个(其中N == cpu内核)任务可以在此调度程序中并行运行.

The difference is that Dispatchers.Default is limited to the number of CPU cores (with a minimum of 2) so only N (where N == cpu cores) tasks can run in parallel in this dispatcher.

在IO分配器上,默认情况下有64个线程,因此该分配器上最多可以运行64个并行任务.

On the IO dispatcher there are by default 64 threads, so there could be up to 64 parallel tasks running on that dispatcher.

想法是IO调度程序花费大量时间等待(IO阻塞),而Default调度程序则用于CPU密集型任务,而这些任务几乎没有睡眠.

The idea is that the IO dispatcher spends a lot of time waiting (IO blocked), while the Default dispatcher is intended for CPU intensive tasks, where there is little or no sleep.

这篇关于使用分派器IO和默认值之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆