bank_account_1.cpp 822 B

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