What is a coroutine?

强颜欢笑 提交于 2020-01-08 23:57:09

问题


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


回答1:


Coroutines and concurrency are largely orthogonal. Coroutines are a general control structure whereby flow control is cooperatively passed between two different routines without returning.

The 'yield' statement in Python is a good example. It creates a coroutine. When the 'yield ' is encountered the current state of the function is saved and control is returned to the calling function. The calling function can then transfer execution back to the yielding function and its state will be restored to the point where the 'yield' was encountered and execution will continue.




回答2:


From Programming in Lua, "Coroutines" section:

A coroutine is similar to a thread (in the sense of multithreading): it is a line of execution, with its own stack, its own local variables, and its own instruction pointer; but it shares global variables and mostly anything else with other coroutines. The main difference between threads and coroutines is that, conceptually (or literally, in a multiprocessor machine), a program with threads runs several threads in parallel. Coroutines, on the other hand, are collaborative: at any given time, a program with coroutines is running only one of its coroutines, and this running coroutine suspends its execution only when it explicitly requests to be suspended.

So the point is: Coroutines are "collaborative". Even in multi-core system, there is only one coroutine running at any given time (but multiple threads can run in parallel). There is non-preemptive between coroutines, the running coroutine must relinquish the execution explicitly.

For "concurrency", you can refer Rob Pike's slide:

Concurrency is the composition of independently executing computations.

So during coroutine A's execution, it passes control to coroutine B. Then after some time, the coroutine B passes control back to coroutine A. Since there is dependency between coroutines, and they must run in tandem, so the two coroutines are not concurrency.




回答3:


I find most of the answers too technical even though it is a technical question. I had a hard time trying to understand the coroutine process. I kind of get it but then I don't get it at the same time.

I found this answer here very helpful:

https://dev.to/thibmaek/explain-coroutines-like-im-five-2d9

To quote from Idan Arye:

To build on your story, I'd put it something like this:

You start watching the cartoon, but it's the intro. Instead of watching the intro you switch to the game and enter the online lobby - but it needs 3 players and only you and your sister are in it. Instead of waiting for another player to join you switch to your homework, and answer the first question. The second question has a link to a YouTube video you need to watch. You open it - and it starts loading. Instead of waiting for it to load, you switch back to the cartoon. The intro is over, so you can watch. Now there are commercials - but meanwhile a third player has joined so you switch to the game And so on...

The idea is that you don't just switch the tasks really fast to make it look like you are doing everything at once. You utilize the time you are waiting for something to happen(IO) to do other things that do require your direct attention.

Definitely check the link, there are much more that I cannot quote everything.




回答4:


Coroutine is similar to subroutine/threads. The difference is once a caller invoked a subroutine/threads, it will never return back to the caller function. But a coroutine can return back to the caller after executing a few piece of code allowing the caller to execute some of its own code and get back to the coroutine point where it stopped execution and continue from there. ie. A coroutine has more than one entry and exit points




回答5:


  • Coroutines are great features available in Kotlin Language
  • Coroutines are a new way of writing asynchronous, non-blocking code (and much more)
  • Coroutine are light-weight threads. A light weight thread means it doesn’t map on native thread, so it doesn’t require context switching on processor, so they are faster.
  • it doesn’t map on native thread
  • Coroutines and the threads both are multitasking. But the difference is that threads are managed by the OS and coroutines by the users.

Basically, there are two types of Coroutines:

  1. Stackless
  2. Stackful

Kotlin implements stackless coroutines — it’s mean that the coroutines don’t have own stack, so they don’t map on native thread.

These are the functions to start the coroutine:

launch{}

async{}

You can learn more from here :

https://www.kotlindevelopment.com/deep-dive-coroutines/

https://blog.mindorks.com/what-are-coroutines-in-kotlin-bf4fecd476e9




回答6:


On a different note, in python gevent library is a coroutine based networking library which gives you threadlike features like async network requests, without the overhead of creating and destroying threads. The coroutine library used is greenlet.




回答7:


From Python Coroutine:

Execution of Python coroutines can be suspended and resumed at many points (see coroutine). Inside the body of a coroutine function, await and async identifiers become reserved keywords; await expressions, async for and async with can only be used in coroutine function bodies.

From Coroutines (C++20)

A coroutine is a function that can suspend execution to be resumed later. Coroutines are stackless: they suspend execution by returning to the caller. This allows for sequential code that executes asynchronously (e.g. to handle non-blocking I/O without explicit callbacks), and also supports algorithms on lazy-computed infinite sequences and other uses.

Compare with other's answer:

In my opinion, the resumed later part is a core difference, just like @Twinkle's.
Although many fields of the document are still work in progress, however, this part is similar to most answer, except @Nan Xiao 's

Coroutines, on the other hand, are collaborative: at any given time, a program with coroutines is running only one of its coroutines, and this running coroutine suspends its execution only when it explicitly requests to be suspended.

Since it's quoted from Program in Lua, maybe it's language related(not familiar with Lua currently), not all document mentioned the only one part.

The relation with concurrent:
There is an "Execution" part of the Coroutines (C++20).Too long to quote here.
Besides the detail, there are several states.

When a coroutine begins execution  
When a coroutine reaches a suspension point  
When a coroutine reaches the co_return statement  
If the coroutine ends with an uncaught exception  
When the coroutine state is destroyed either because it terminated via co_return or uncaught exception, or because it was destroyed via its handle 

as the comment from @Adam Arold under @user217714's answer. It's concurrency.
But it's different from multithreading. from std::thread

Threads allow multiple functions to execute concurrently. Threads begin execution immediately upon construction of the associated thread object (pending any OS scheduling delays), starting at the top-level function provided as a constructor argument. The return value of the top-level function is ignored and if it terminates by throwing an exception, std::terminate is called. The top-level function may communicate its return value or an exception to the caller via std::promise or by modifying shared variables (which may require synchronization, see std::mutex and std::atomic)

Since it's concurrency, it works like multithreading especially when waiting is unavoidable(from the OS perspective), that's also why it's confusing.



来源:https://stackoverflow.com/questions/553704/what-is-a-coroutine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!