]>
Commit | Line | Data |
---|---|---|
1 | #include <boost/asio/ts/executor.hpp> | |
2 | #include <boost/asio/thread_pool.hpp> | |
3 | #include <iostream> | |
4 | ||
5 | using boost::asio::post; | |
6 | using boost::asio::thread_pool; | |
7 | using boost::asio::use_future; | |
8 | ||
9 | // Traditional active object pattern. | |
10 | // Member functions block until operation is finished. | |
11 | ||
12 | class bank_account | |
13 | { | |
14 | int balance_ = 0; | |
15 | mutable thread_pool pool_{1}; | |
16 | ||
17 | public: | |
18 | void deposit(int amount) | |
19 | { | |
20 | post(pool_, | |
21 | use_future([=] | |
22 | { | |
23 | balance_ += amount; | |
24 | })).get(); | |
25 | } | |
26 | ||
27 | void withdraw(int amount) | |
28 | { | |
29 | post(pool_, | |
30 | use_future([=] | |
31 | { | |
32 | if (balance_ >= amount) | |
33 | balance_ -= amount; | |
34 | })).get(); | |
35 | } | |
36 | ||
37 | int balance() const | |
38 | { | |
39 | return post(pool_, | |
40 | use_future([=] | |
41 | { | |
42 | return balance_; | |
43 | })).get(); | |
44 | } | |
45 | }; | |
46 | ||
47 | int main() | |
48 | { | |
49 | bank_account acct; | |
50 | acct.deposit(20); | |
51 | acct.withdraw(10); | |
52 | std::cout << "balance = " << acct.balance() << "\n"; | |
53 | } |