Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. //
  2. // main.cpp
  3. // PPD lab1
  4. //
  5. // Created by Gabriel Goteciuc on 12/10/2019.
  6. // Copyright © 2019 Gabriel Goteciuc. All rights reserved.
  7. //
  8.  
  9. #include "main.hpp"
  10.  
  11. MARKET m;
  12. std::mutex historyMtx;
  13.  
  14. int noOfThreads;
  15.  
  16. std::vector<BILL> bills;
  17.  
  18. void runCheck() {
  19. int sum = 0;
  20. historyMtx.lock();
  21.  
  22. for (int i = 0; i < MAX_PRODUCTS; ++i) {
  23. m.products[i].mtx.lock();
  24. }
  25.  
  26. m.mtx.lock();
  27.  
  28. for (int i = 0; i < bills.size(); ++i) {
  29. for (auto it:bills[i].orders) {
  30. sum += m.products[it.first].price * it.second;
  31. }
  32. }
  33.  
  34. if (sum != m.balance) {
  35. std::cout << "Error in balance\n";
  36. } else {
  37. std::cout << "Balance " << m.balance << " is correct\n";
  38. }
  39.  
  40. m.mtx.unlock();
  41.  
  42. for (int i = 0; i < MAX_PRODUCTS; ++i) {
  43. m.products[i].mtx.unlock();
  44. }
  45.  
  46. historyMtx.unlock();
  47.  
  48. }
  49.  
  50. void processBill() {
  51. int sum = 0;
  52. std::vector<std::pair<int, int>> orders;
  53.  
  54. historyMtx.lock();
  55. bills.push_back(BILL());
  56.  
  57. for (int i = 0; i < 4; ++i) {
  58. int product = rand() % MAX_PRODUCTS;
  59. int quantity = rand() % 5;
  60.  
  61. orders.push_back(std::make_pair(product, quantity));
  62. bills.back().orders.push_back(std::make_pair(product, quantity));
  63. }
  64. historyMtx.unlock();
  65.  
  66. std::sort(orders.begin(), orders.end());
  67.  
  68. for (auto it:orders) {
  69. m.products[it.first].mtx.lock();
  70. }
  71.  
  72. for (auto it:orders) {
  73. sum += m.products[it.first].price * it.second;
  74. m.products[it.first].amount -= it.second;
  75. }
  76.  
  77. m.mtx.lock();
  78.  
  79. for (auto it:orders) {
  80. m.products[it.first].mtx.unlock();
  81. }
  82.  
  83. m.balance += sum;
  84.  
  85. m.mtx.unlock();
  86. }
  87.  
  88. void worker() {
  89. for (int i = 0; i < 5000; ++i) {
  90. if (rand() % 1000 == 1) {
  91. runCheck();
  92. continue;
  93. }
  94.  
  95. processBill();
  96. }
  97. }
  98.  
  99. std::thread threads[100];
  100.  
  101. int main() {
  102. noOfThreads = 2;
  103.  
  104. srand ((unsigned)time(NULL));
  105.  
  106. for (int i = 0; i < MAX_PRODUCTS; ++i) {
  107. m.products[i].amount = MAX_AMOUNT;
  108. m.products[i].id = i;
  109. m.products[i].price = rand() % 10 + 1;
  110. }
  111.  
  112. for (int i = 0; i < noOfThreads; ++i) {
  113. threads[i] = std::thread (worker);
  114. }
  115.  
  116. for (int i = 0; i < noOfThreads; ++i) {
  117. threads[i].join();
  118. }
  119.  
  120. runCheck();
  121.  
  122. return 0;
  123. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement