forked from rbouqueau/executors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbank_account_5.cpp
85 lines (76 loc) · 2.04 KB
/
bank_account_5.cpp
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
82
83
84
85
#include <experimental/future>
#include <experimental/strand>
#include <iostream>
using std::experimental::dispatch;
using std::experimental::strand;
using std::experimental::system_executor;
using std::experimental::use_future;
using std::experimental::wrap;
// Active object sharing a system-wide pool of threads.
// The caller chooses how to wait for the operation to finish.
// Lightweight, immediate execution using dispatch.
// Composition using variadic dispatch.
class bank_account
{
int balance_ = 0;
mutable strand<system_executor> ex_;
public:
template <class CompletionToken>
auto deposit(int amount, CompletionToken&& token)
{
return dispatch(ex_, [=]
{
balance_ += amount;
},
std::forward<CompletionToken>(token));
}
template <class CompletionToken>
auto withdraw(int amount, CompletionToken&& token)
{
return dispatch(ex_, [=]
{
if (balance_ >= amount)
balance_ -= amount;
},
std::forward<CompletionToken>(token));
}
template <class CompletionToken>
auto balance(CompletionToken&& token) const
{
return dispatch(ex_, [=]
{
return balance_;
},
std::forward<CompletionToken>(token));
}
template <class CompletionToken>
auto transfer(int amount, bank_account& to_acct, CompletionToken&& token)
{
return dispatch(
wrap(ex_, [=]
{
if (balance_ >= amount)
{
balance_ -= amount;
return amount;
}
return 0;
}),
wrap(to_acct.ex_,
[&to_acct](int deducted)
{
to_acct.balance_ += deducted;
}),
std::forward<CompletionToken>(token));
}
};
int main()
{
bank_account acct1, acct2;
acct1.deposit(20, use_future).get();
acct2.deposit(30, use_future).get();
acct1.withdraw(10, use_future).get();
acct2.transfer(5, acct1, use_future).get();
std::cout << "Account 1 balance = " << acct1.balance(use_future).get() << "\n";
std::cout << "Account 2 balance = " << acct2.balance(use_future).get() << "\n";
}