04-timer5.cpp
1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//
// timer.cpp
// ~~~~~~~~~
//
// Copyright (c) 2003-2020 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 <asio.hpp>
class printer
{
public:
printer(asio::io_context& io)
: strand_(asio::make_strand(io)),
timer1_(io, asio::chrono::seconds(1)),
timer2_(io, asio::chrono::seconds(1)),
count_(0)
{
timer1_.async_wait(asio::bind_executor(strand_,
std::bind(&printer::print1, this)));
timer2_.async_wait(asio::bind_executor(strand_,
std::bind(&printer::print2, this)));
}
~printer()
{
std::cout << "Final count is " << count_ << std::endl;
}
void print1()
{
if (count_ < 10)
{
std::cout << "Timer 1: " << count_ << std::endl;
++count_;
timer1_.expires_at(timer1_.expiry() + asio::chrono::seconds(1));
timer1_.async_wait(asio::bind_executor(strand_,
std::bind(&printer::print1, this)));
}
}
void print2()
{
if (count_ < 10)
{
std::cout << "Timer 2: " << count_ << std::endl;
++count_;
timer2_.expires_at(timer2_.expiry() + asio::chrono::seconds(1));
timer2_.async_wait(asio::bind_executor(strand_,
std::bind(&printer::print2, this)));
}
}
private:
asio::strand<asio::io_context::executor_type> strand_;
asio::steady_timer timer1_;
asio::steady_timer timer2_;
int count_;
};
int main()
{
asio::io_context io;
printer p(io);
// std::thread t(std::bind(&asio::io_context::run, &io));
std::thread t([&io]{io.run();});
io.run();
t.join();
return 0;
}