COROUTINES INTRODUCTION

来源:https://blog.panicsoftware.com/coroutines-introduction/

虽然协程作为重要特性,即将进入 C++ 20,但仍然有很多人吐槽。

Main complaints were regarding the hardness to understand, lots of customisation points, and possibly not optimal performance due to possibly unoptimised dynamic memory allocations

主要的抱怨是关于理解起来很难,大量的定制点以及,未优化的动态内存分配可能造成性能的损失。

谷歌的提案存在一些问题,最终被接受的协程方案来自微软。

什么是协程

The coroutines already exist in many programming languages, may it be Python or C#. Coroutines provide one more way to create asynchronous code. How this way differs from threads and why do we need a dedicated language feature for coroutines and finally how we can benefit will be explained in this section.

协程和线程有什么不同?为什么我们需要协程的专用语言功能?我们从协程中能获得哪些好处?在这一节会给出答案。

Depending on the environment in which they are used they might be called:

  • stackless coroutines
  • stackful coroutines
  • green threads
  • fibers
  • goroutines

Good news is that stackful coroutines, green threads, fibres, goroutines are the same thing (sometimes used differently).

协程库 vs 语言特性

实现协程功能的库,都是有栈协程吗?

此章节作者介绍了 Stackful coroutines 的特性和实现。针对 Stackful coroutines 和 Stackless coroutines 做了比较(前者是库,后者是语言特性)。

Stackful coroutines

Fibers or stackful coroutines are, a separate stack, that can be used to process function calls.

First of all, threads and fibers have their own separate stacks.

首先,线程和纤维有自己独立的栈。

每次 suspend 时 frame(on fiber stack) 保留,切回 fram on the thread stack,resume 时再次回到原 frame。—— 理解正确吗?

Stackless coroutines

So first of all, if they do not allocate the memory for the stack, then how do they work? Where goes all the data meant to be stored on the stack in case of the stackful coroutines? The answer is: on the caller’s stack.

无栈协程不是不使用栈:区分于有栈协程单独分配栈存储,无栈协程并不额外分配栈,而是使用调用方的栈。

The secret of stackless coroutines is that they can suspend themselves only from the top-level function.

无栈协程只能在顶层函数暂停执行。

每次 suspend 时 frame 释放掉(pop),resume 的时候由 coroutine object (as local variable on the caller’s frame) 再次建立 frame。—— 参考 coroutine-theory 的 The ‘Resume’ operation 章节。