协程概念

协程就是一种用户态内的上下文切换技术

 

我对协程的定义是:协程是在一个线程执行过程中可以在一个子程序的预定或者随机位置中断,然后转而执行别的子程序,在适当的时候再返回来接着执行。他本身是一种特殊的子程序或者称作函数。

区别:楼上很好很精辟。

应用:协程基于generator,Python3中内置了异步IO。遇到IO密集型的业务时,总是很费时间啦,多线程加上协程,你磁盘在那该读读该写写,我还能去干点别的。在WEB应用中效果尤为明显。


作者:如此这般
链接:https://www.zhihu.com/question/35139020/answer/61705846
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

关键词:协程 栈帧 指令 切换 跳转

 

异步结果的等待、后继计算的保存。 

 

Coroutines are computer program components that generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and resumed. Coroutines are well-suited for implementing familiar program components such as cooperative tasks, exceptions, event loops, iterators, infinite lists and pipes.

 

Python 3.5 introduces explicit support for coroutines with async/await syntax 

 

Comparison with threads[edit]

Coroutines are very similar to threads. However, coroutines are cooperatively multitasked, whereas threads are typically preemptively multitasked. This means that coroutines provide concurrency but not parallelism. T

 

var q := new queue

 

coroutine produce

    loop

        while q is not full

            create some new items

            add the items to q

        yield to consume

 

coroutine consume

    loop

        while q is not empty

            remove some items from q

            use the items

        yield to produce

 

Implementations for C[edit]

In order to implement general-purpose coroutines, a second call stack must be obtained, which is a feature not directly supported by the C language. 

 

 

Implementations for Rust[edit]

There is a library for Rust that provides coroutines.[45] Generators are an experimental feature available in nightly rust that provides an implementation of coroutines with async/await.[46]

 

posted @ 2019-03-05 19:48  zzfx  阅读(483)  评论(0编辑  收藏  举报