1 //
2 // timer.cpp
3 // ~~~~~~~~~
4 //
5 // Copyright (c) 2003-2021 Christopher M. Kohlhoff (chris at kohlhoff dot com)
6 //
7 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
9 //
10
11 #include <iostream>
12 #include <boost/asio.hpp>
13 #include <boost/thread/thread.hpp>
14 #include <boost/bind/bind.hpp>
15
16 class printer
17 {
18 public:
printer(boost::asio::io_context & io)19 printer(boost::asio::io_context& io)
20 : strand_(boost::asio::make_strand(io)),
21 timer1_(io, boost::asio::chrono::seconds(1)),
22 timer2_(io, boost::asio::chrono::seconds(1)),
23 count_(0)
24 {
25 timer1_.async_wait(boost::asio::bind_executor(strand_,
26 boost::bind(&printer::print1, this)));
27
28 timer2_.async_wait(boost::asio::bind_executor(strand_,
29 boost::bind(&printer::print2, this)));
30 }
31
~printer()32 ~printer()
33 {
34 std::cout << "Final count is " << count_ << std::endl;
35 }
36
print1()37 void print1()
38 {
39 if (count_ < 10)
40 {
41 std::cout << "Timer 1: " << count_ << std::endl;
42 ++count_;
43
44 timer1_.expires_at(timer1_.expiry() + boost::asio::chrono::seconds(1));
45
46 timer1_.async_wait(boost::asio::bind_executor(strand_,
47 boost::bind(&printer::print1, this)));
48 }
49 }
50
print2()51 void print2()
52 {
53 if (count_ < 10)
54 {
55 std::cout << "Timer 2: " << count_ << std::endl;
56 ++count_;
57
58 timer2_.expires_at(timer2_.expiry() + boost::asio::chrono::seconds(1));
59
60 timer2_.async_wait(boost::asio::bind_executor(strand_,
61 boost::bind(&printer::print2, this)));
62 }
63 }
64
65 private:
66 boost::asio::strand<boost::asio::io_context::executor_type> strand_;
67 boost::asio::steady_timer timer1_;
68 boost::asio::steady_timer timer2_;
69 int count_;
70 };
71
main()72 int main()
73 {
74 boost::asio::io_context io;
75 printer p(io);
76 boost::thread t(boost::bind(&boost::asio::io_context::run, &io));
77 io.run();
78 t.join();
79
80 return 0;
81 }
82