Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // main.cpp
- // PPD lab1
- //
- // Created by Gabriel Goteciuc on 12/10/2019.
- // Copyright © 2019 Gabriel Goteciuc. All rights reserved.
- //
- #include "main.hpp"
- MARKET m;
- std::mutex historyMtx;
- int noOfThreads;
- std::vector<BILL> bills;
- void runCheck() {
- int sum = 0;
- historyMtx.lock();
- for (int i = 0; i < MAX_PRODUCTS; ++i) {
- m.products[i].mtx.lock();
- }
- m.mtx.lock();
- for (int i = 0; i < bills.size(); ++i) {
- for (auto it:bills[i].orders) {
- sum += m.products[it.first].price * it.second;
- }
- }
- if (sum != m.balance) {
- std::cout << "Error in balance\n";
- } else {
- std::cout << "Balance " << m.balance << " is correct\n";
- }
- m.mtx.unlock();
- for (int i = 0; i < MAX_PRODUCTS; ++i) {
- m.products[i].mtx.unlock();
- }
- historyMtx.unlock();
- }
- void processBill() {
- int sum = 0;
- std::vector<std::pair<int, int>> orders;
- historyMtx.lock();
- bills.push_back(BILL());
- for (int i = 0; i < 4; ++i) {
- int product = rand() % MAX_PRODUCTS;
- int quantity = rand() % 5;
- orders.push_back(std::make_pair(product, quantity));
- bills.back().orders.push_back(std::make_pair(product, quantity));
- }
- historyMtx.unlock();
- std::sort(orders.begin(), orders.end());
- for (auto it:orders) {
- m.products[it.first].mtx.lock();
- }
- for (auto it:orders) {
- sum += m.products[it.first].price * it.second;
- m.products[it.first].amount -= it.second;
- }
- m.mtx.lock();
- for (auto it:orders) {
- m.products[it.first].mtx.unlock();
- }
- m.balance += sum;
- m.mtx.unlock();
- }
- void worker() {
- for (int i = 0; i < 5000; ++i) {
- if (rand() % 1000 == 1) {
- runCheck();
- continue;
- }
- processBill();
- }
- }
- std::thread threads[100];
- int main() {
- noOfThreads = 2;
- srand ((unsigned)time(NULL));
- for (int i = 0; i < MAX_PRODUCTS; ++i) {
- m.products[i].amount = MAX_AMOUNT;
- m.products[i].id = i;
- m.products[i].price = rand() % 10 + 1;
- }
- for (int i = 0; i < noOfThreads; ++i) {
- threads[i] = std::thread (worker);
- }
- for (int i = 0; i < noOfThreads; ++i) {
- threads[i].join();
- }
- runCheck();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement