Member-only story

Painless C++ Coroutines-Part 1

Gajendra Gulgulia
9 min readMay 31, 2021

--

Incidentally I found the mechanics of coroutines quite obfuscating given the number of implicit and under-the-hood calls to several methods associated with coroutine and their return type objects. Even with tons of articles and posts on the web, I started to have a feeling that coroutines is an arcane feature that can be understood by the very few who are either in committee or are renowned authors of blogs, books and articles or experienced C++ library authors.

But after a month of arduous efforts and experiments, trials and errors to understand coroutine, I decided to write a tutorial series that can be used by any intermediate C++ developer to understand coroutine .

Introduction

C++ 20’s coroutines are a tough nut to crack and cannot be explained in a mere few lines. My post is organized in incremental sections and explains the coroutine mechanics in great details in 12 sections split in 5 parts (i.e. 5 articles in the tutorial series) with tons of examples and code snippets. Each section is written with details that builds up on the details from previous section. Efforts have been made to lay out the idea, that I understood from my experiments and understanding, of why something has to be done the way it has been.

Before starting, I emphasize that this series is not an article that one expects to take away something from by a cursory read. Rather it is a tutorial series that may strike chords with only those who are seriously committed to understanding the coroutines and for them the piece of advice is to try out the example codes and experiment with them. Even the playing with the pseudocodes I provide in the beginning can be helpful in the form of compiler errors.

1. What are coroutines?

I’ll first quote important points from cpp reference page on when a function can be a coroutine

A function is a coroutine if its definition does any of the following:
1. uses the co_await operator to suspend execution ...
2. keyword co_yield to suspend execution returning a value ...
3. keyword co_return to complete execution returning a value ...

Next the restrictions on a coroutine as per the cpp reference page:

Coroutines cannot use variadic arguments…

--

--

Gajendra Gulgulia
Gajendra Gulgulia

Written by Gajendra Gulgulia

I'm a backend software developer and modern C++ junkie. I run a modern cpp youtube channel (https://www.youtube.com/@masteringmoderncppfeatures6302/videos)

No responses yet

The author has closed discussion for this story. Learn more.