![]() |
Home | Libraries | People | FAQ | More |
// // timer.cpp // ~~~~~~~~~ // // Copyright (c) 2003-2026 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <iostream> #include <thread> #include <boost/asio.hpp> 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)); 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(); } } 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); boost::asio::co_spawn(s, print(1, &count), boost::asio::detached); boost::asio::co_spawn(s, print(2, &count), boost::asio::detached); std::thread t([&]{ io.run(); }); io.run(); t.join(); std::cout << "Final count is " << count << std::endl; return 0; }
Return to Timer.8 - Synchronising coroutines in multithreaded programs