Advertisement
Guest User

Untitled

a guest
Aug 17th, 2019
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1.  
  2. #include <iostream>
  3. #include <mutex>
  4. #include <thread>
  5. #include <vector>
  6.  
  7. struct Account
  8. {
  9.     double money;
  10.     std::mutex m;
  11.     Account() : money(0.0), m() {}
  12. };
  13.  
  14. void change(uint32_t iter, Account &acc1, double dif1, Account &acc2, double dif2)
  15. {
  16.     for (uint32_t i = 0; i < iter; ++i) {
  17.         std::scoped_lock lock(acc1.m, acc2.m);
  18.         acc1.money += dif1;
  19.         acc2.money += dif2;
  20.     }
  21. }
  22.  
  23. int main() {
  24.     uint32_t acc_count, thr_count;
  25.     std::cin >> acc_count >> thr_count;
  26.     std::vector<Account> accounts(acc_count);
  27.  
  28.     std::vector<std::thread> threads;
  29.  
  30.  
  31.     for (uint32_t i = 0; i < thr_count; ++i) {
  32.         uint32_t iter, id1, id2;
  33.         double dif1, dif2;
  34.         std::cin >> iter >> id1 >> dif1 >> id2 >> dif2;
  35.         if (id1 < id2) {
  36.             threads.emplace_back(change, iter, std::ref(accounts[id1]), dif1, std::ref(accounts[id2]), dif2);
  37.         } else {
  38.             threads.emplace_back(change, iter, std::ref(accounts[id2]), dif2, std::ref(accounts[id1]), dif1);
  39.         }
  40.     }
  41.  
  42.     for (auto &t : threads) {
  43.         t.join();
  44.     }
  45.  
  46.     for (auto &a : accounts) {
  47.         printf("%.10g\n", a.money);
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement