Advertisement
RobertDeMilo

RB5.19 mutex и lock guard

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