Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <thread>
- #include <mutex>
- #include <chrono>
- using namespace std;
- mutex mutexBank;
- int minMoney = 5000;
- int currentMoney = 10000;
- int depositMoney = 250;
- int creditMoney = 500;
- void creditThreadFunction() {
- while (true) {
- mutexBank.lock(); // Започваме критична секция
- if (currentMoney - creditMoney <= minMoney) {
- // Няма достатъчно средства, правим пауза
- mutexBank.unlock(); // Освобождаваме мютекса, преди да заспим
- this_thread::sleep_for(chrono::seconds(6));
- } else {
- // Намаляваме текущите средства
- currentMoney -= creditMoney;
- mutexBank.unlock(); // Освобождаваме мютекса след теглене
- this_thread::sleep_for(chrono::seconds(1));
- }
- }
- }
- void depositThreadFunction() {
- while (true) {
- mutexBank.lock(); // Започваме критична секция
- currentMoney += depositMoney; // Увеличаваме текущите средства
- mutexBank.unlock(); // Освобождаваме мютекса след внасяне
- this_thread::sleep_for(chrono::seconds(1));
- }
- }
- int main()
- {
- thread *t1, *t2, *t3, *t4;
- t1 = new thread(creditThreadFunction);
- t2 = new thread(creditThreadFunction);
- t3 = new thread(depositThreadFunction);
- t4 = new thread(depositThreadFunction);
- while (true) {
- mutexBank.lock();
- printf("Main Money: %d\n", currentMoney);
- mutexBank.unlock();
- this_thread::sleep_for(chrono::seconds(1)); // Пауза между проверките
- }
- t1->join();
- t2->join();
- t3->join();
- t4->join();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement