What is a coroutine?

前端 未结 10 1928
闹比i
闹比i 2020-11-28 17:27

What is a coroutine? How are they related to concurrency?

10条回答
  •  北海茫月
    2020-11-28 17:55

    I will expand on @user21714 's answer. Coroutines are independent paths of execution that can not run simultaneously. They depend upon a controller - for example a python controller library - to handle switching between these paths. But for this to work the coroutines themselves need to invoke yield or similar structures that allow their execution to be paused.

    Threads instead are running on independent compute resources and in parallel with each other. Since they are on different resources there is no need for invoking yield to allow the other paths of execution to proceed.

    You can see this effect by starting a multihreaded program - e.g. a jvm application - in which all eight of your core i7 hyperthread cores are utilized: you might see 797% utilization in Activity Monitor or Top. Instead when running a typical python program - even one with coroutines or python threading - the utilization will max out at 100%. I.e. one machine hyperthread.

提交回复
热议问题