What is a coroutine?

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

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

10条回答
  •  死守一世寂寞
    2020-11-28 18:12

    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.

提交回复
热议问题