java - python的协程是什么?和多线程有啥区别吗?
高洛峰
高洛峰 2017-04-18 10:03:13
0
4
601

这才刚刚学完多线程,最近在知乎https://zhuanlan.zhihu.com/p/...又看到协程这个概念,但是文章讲的我不明不白,而且前面只提到了协程相比多线程的三个优点,请问协程究竟是什么?他各有什么优缺点?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(4)
巴扎黑

Coroutines are similar to threads, but threads are provided by the bottom layer of the operating system, while coroutines are provided by the platform itself.
Coroutines are based on threads. The bottom layer of a coroutine library is supported by operating system threads, and then the library completes task scheduling by itself without relying on system scheduling.
The advantages of coroutines have been mentioned in the link you posted, but the disadvantage is that the implementation is more complicated, and the actual performance will be lower than using threads directly.

巴扎黑

Coroutines are actually function calls, which are more lightweight than threads. For details, you can view coroutines

伊谢尔伦
def 协程1():
    pass
def 协程2():
    pass
def 协程3():
    pass
def 协程n():
    pass

while 1:
    协程1()
    协程2()
    协程3()
    协程n()

Coroutines are functions that are called in an infinite loop.
The above is the basic idea of ​​coroutines. There is nothing mysterious~
It needs to be used with asynchronous IO to avoid blocking~

巴扎黑

The concept of coroutines is explained in detail in the link on the second floor. You can also learn about gevent. A coroutine based library. After understanding this, I believe you will have a better understanding of coroutines

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!