guodongxiaren/Blog

[译]C++20:关于协程的更多详细讨论

Opened this issue · 2 comments

在你读完我上一篇文章C++20: 协程一瞥之后,今天我更为详细地再谈一下协程。
再一次,我们再C++20中没有见到coroutines(协程),但是我们可以创造一些框架来实现协程。
image

这篇以及后续的文章中我将介绍一个实现协程的框架。最终,你将创造一个你自己的,或者使用一个已经存在的协程实现(比如: Lewis Baker的天才之作:cppcoro

今天这篇文章是中间的一篇:这篇文章不是概述,但也不是深入探讨。下一篇文章将深入探讨协程框架。

你的第一个问题:什么时候我应该使用协程?

典型的使用场景

协程通常用于编写事件驱动的应用,事件驱动应用可以是仿真、游戏、服务器、UI甚至算法。例如,几年前我用Python为去纤颤器写了一个仿真程序。这个仿真程序帮助我们临床研究。去纤颤器是一个事件驱动应用,我基于Python的twisted框架实现了它。
协程也用于多任务协作。

Coroutines are also typically used for cooperative multitasking. The key to cooperative multitasking is that each task takes as much time as it needs. Cooperative multitasking stands in contrast to preemptive multitasking, for which we have a scheduler that decides how long each task gets the CPU. Cooperative multitasking makes concurrency often easier because a concurrent job can not be interrupted in a critical region. If you are still puzzled with the terms cooperative and preemptive, I found an excellent overview and read here: Cooperative vs. Preemptive: a quest to maximize concurrency power