bank_account_2.cpp 959 B

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