Mri*_*jay 9 asynchronous coroutine kotlin kotlin-coroutines
就异步编程而言,这可能是一个非常基本的问题,但是我尝试阅读有关该内容的信息,但找不到相同的任何资源。
假设:我对异步编程有一个总体思路:
当开始阻塞操作(网络调用,从数据库/文件读取)时,我们可以将其委派给内核线程,这将使我们的应用程序线程可用于其他作业。内核线程等待作业完成,并在作业完成时向应用程序线程提供回调。
协程:最近几天我一直在阅读有关Kotlin协程的信息。我认为明智的协程在语言上是不可知的。我一直得到的问题是:
如何suspension和continuation发生的协同例程。协程不是线程(操作系统给它们分配了处理器的一部分),而是tasks在要执行的线程上调度的。
谁一直在寻找正在执行的程序,并说此协程已达到挂起点,应将其从线程中删除。continuation应该在该线程上调度另一个需要从中重新启动的协程。至于我已经读过的Java Fibers将由a完成Fiber Scheduler,在Kotlin中是否类似?
预先感谢您的帮助。
Coroutine suspension is entirely explicit and first-class. It happens when you call suspendCoroutine() or suspendCancellableCoroutine(), passing in a block that receives the continuation as the parameter.
The block can do whatever it wants with the continuation object, and when someone, somewhere, calls continuation.resume(resultValue(), it will resume. The thread it resumes on is initially the thread that calls resume(), but the logic inside resume immediately delegates to the Dispatcher in charge, which then typically submits the resumption to another thread or thread pool.
The Dispatcher logic is again first-class and you can write your own dispatcher. However, this is almost never needed because there are only a handful of meaningful ways to do it, and Kotlin already supports them.
You can also review a concrete example in code that demonstrates the naked usage of suspendCoroutine and coroutine.resume(), without the layer the Dispatcher adds to it.
顺便说一句,您永远不会将阻止操作委托给“内核线程”以使它们成为非阻止的。异步操作不会阻塞任何线程。在底层,例如,有一个选择器的机制,可以在IO操作完成时接收事件。它的工作原理很像GUI线程中的事件循环。
| 归档时间: |
|
| 查看次数: |
161 次 |
| 最近记录: |