Advertisement
RobertDeMilo

BB4.15 RAII вокруг нас

Jun 21st, 2024
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. #include<iostream>
  2. #include<cstdint>
  3. #include<vector>
  4. #include<future>
  5. #include<mutex>
  6. using namespace std;
  7.  
  8. struct Account
  9. {
  10.     int balance = 0;
  11.     mutex m;
  12.  
  13.     bool Spend(int value)
  14.     {
  15.         lock_guard<mutex> guard(m);
  16.         //m.lock();
  17.         if (value <= balance)
  18.         {
  19.             balance -= value;
  20.            //m.unlock();
  21.             return true;
  22.         }
  23.         //m.unlock();
  24.         return false;
  25.     }
  26. };
  27.  
  28. int SpendMoney(Account& account)
  29. {
  30.     int total_spent = 0;
  31.     for (int i = 0; i < 100000; ++i)
  32.     {
  33.         if (account.Spend(1))
  34.         {
  35.             ++total_spent;
  36.         }
  37.     }
  38.     return total_spent;
  39. }
  40.  
  41. int main()
  42. {
  43.     Account family_account{ 100000 };
  44.  
  45.     auto husband = async(SpendMoney, ref(family_account));
  46.     auto wife = async(SpendMoney, ref(family_account));
  47.     auto son = async(SpendMoney, ref(family_account));
  48.     auto daughter = async(SpendMoney, ref(family_account));
  49.  
  50.     int spent = husband.get() + wife.get() + son.get() + daughter.get();
  51.  
  52.     cout << "Total spent: " << spent << endl
  53.         << "Balance: " << family_account.balance << endl;
  54.     /*cout << "Total spent: " << SpendMoney(family_account) << endl
  55.         << "Balance: " << family_account.balance << endl;*/
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement