I gave in my last post, “C++20: Coroutines with cppcoro“, a basic introduction to the coroutines library from Lewis Baker. This introduction covered the elementary coroutines task and generator. Today, I add threads to tasks and get powerful abstractions.
Do you remember the previous post “C++20: Thread Synchronization with Coroutines“? If no, I presented the challenges of a condition variable. A condition variable is a classical thread synchronization method, such as in a sender/receiver or a producer/consumer workflow. Condition variables have a big design flaw; they may be invoked without a notification (spurious wakeup) or overhear the notification (lost wakeup). In both cases, you may get a deadlock. My following example on thread synchronization based on coroutines didn’t have the inherent risk of condition variables such as spurious or lost wakeup, but the example had another issue. It was too complicated.
Thanks to cppcoro, we can have the best of both worlds.: a straightforward event mechanism that does not have the design flaws of condition variables.
single_consumer_event is, according to the documentation, a simple manual-reset event type that supports only a single coroutine awaiting it at a time. This is precisely, what I need:
The code should be self-explanatory. The consumer (line 1) and the producer (line 2) run in their thread. The call cppcoro::sync_wait(consumer()) (line 1) serves as a top-level task because the main function cannot be a coroutine. The call waits until the coroutine consumer is done. The coroutine consumer waits in the call co_await event until someone calls event.set(). The function producer sends this event after a sleep of two seconds.
Thanks to the cppcoro library, threads can be canceled.
The caller and the callee communicate with the cppcoro::cancellation_token. The callee of the function that gets the request to cancel can respond in two ways.
- Poll at regular intervals for the request to cancel. The cppcoro::cancellation_token supports two member functions: is_cancellation_requested() and throw_if_cancellation_requested().
- Register a callback that is executed in case of a cancellation request.
The following example exemplifies the first use case.
Line (1) shows the cancellation_token, created by the cancellation_source. The caller cancelSender gets the cancellation source canSource, and the callee cancelReceiver gets the cancellation token. The callee polls permanently for the cancellation request (line 2), which the caller sends via the call call.request_cancellation() (line 3) after two seconds.
I want to make two interesting observations.
- The cancellation is cooperative. If the callee ignores that cancellation request, nothing happens.
- We get with C++20 an improved std::thread: std::jthread. std::jthread joins automatically in its destructor and can be in interrupted via an interrupt token. Read more details about the improved std::thread in my previous post: “A new Thread with C++20: std::jthread“.
cppcoro even supports a mutex.
A mutex such as cppcoro::async_mutex is a synchronization mechanism to protect shared data from being accessed by multiple threads simultaneously.
Line (1) creates ten threads. Each thread adds the numbers 0 to 9 to the shared sum (line 2). The function addToSum is the coroutine. The coroutine waits in the expression co_await mutex.scoped_lock_async() (line 3) until the mutex is acquired. The coroutine that waits for the mutex is not blocked but suspended. The previous lock-holder resumes the waiting coroutine in its unlock call. As its name suggests, the mutex stays locked until the end of the scope (line 4).
Thanks to the function cppcoro::when_all, you can wait on one and more coroutines. I use cppcoro::when_all with cppcoro::static_thread_pool in my next post to compose powerful workflows.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, and Marco Parri Empoli.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,