![]() |
Home | Libraries | People | FAQ | More |
This tutorial demonstrates the use of the strand class template to synchronise coroutines in a multithreaded program. It is a rewrite of the program from tutorial Timer.5. This tutorial program requires a compiler that supports C++20 coroutines.
#include <iostream> #include <thread> #include <boost/asio.hpp>
In tutorial Timer.5 we needed a separate member function for each timer.
Now that the timer is a local variable of the coroutine, a single coroutine
function will serve for both timers. We pass it an id
to use in its output, and a pointer to the counter that the two coroutines
share.
boost::asio::awaitable<void> print(int id, int* count) { boost::asio::steady_timer t(co_await boost::asio::this_coro::executor, boost::asio::chrono::seconds(1));
The loop is similar to the one in tutorial Timer.7, except that the counter is shared between the two coroutines, and each coroutine stops when the counter reaches 10.
co_await t.async_wait(); while (*count < 10) { std::cout << "Timer " << id << ": " << *count << std::endl; ++(*count); t.expires_at(t.expiry() + boost::asio::chrono::seconds(1)); co_await t.async_wait(); } }
The main function declares
the counter, then creates an boost::asio::strand<boost::asio::io_context::executor_type>
object.
int main() { boost::asio::io_context io; int count = 0; boost::asio::strand<boost::asio::io_context::executor_type> s = boost::asio::make_strand(io);
We start both coroutines using boost::asio::co_spawn(), passing the strand as the executor that they will run on. A coroutine is always resumed on its executor, so every part of each coroutine runs through the strand. Unlike tutorial Timer.5, there is no need to bind each completion handler to the strand using boost::asio::bind_executor().
The shared resources used by the coroutines are std::cout
and the counter. By running both coroutines on the same strand, we are ensuring
that they cannot execute concurrently.
boost::asio::co_spawn(s, print(1, &count), boost::asio::detached); boost::asio::co_spawn(s, print(2, &count), boost::asio::detached);
As in tutorial Timer.5, boost::asio::io_context::run() is called from two threads: the main thread and one additional thread. Both calls return once the coroutines have finished.
std::thread t([&]{ io.run(); }); io.run(); t.join();
Finally, we print the final value of the counter.
std::cout << "Final count is " << count << std::endl; return 0; }
See the full source listing
Return to the tutorial index
Previous: Timer.7 - Using a coroutine to implement a repeating timer