Home  >  Q&A  >  body text

java - python的协程是什么?和多线程有啥区别吗?

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

高洛峰高洛峰2713 days ago563

reply all(4)I'll reply

  • 巴扎黑

    巴扎黑2017-04-18 10:05:13

    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.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 10:05:13

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

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:05:13

    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~

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 10:05:13

    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

    reply
    0
  • Cancelreply