#include "JLang/JMutex.hh" #include #include #include #include "Jeep/JParser.hh" #include "Jeep/JMessage.hh" /** * \author cpellegrino */ using namespace JPP; void withdraw(int& account, int amount) { if (amount < 0) throw std::runtime_error("Wrong amount!"); if (account < amount) throw std::runtime_error("Your account can't provide the requested amount!"); account -= amount; } void deposit(int& account, int amount) { if (amount < 0) throw std::runtime_error("Wrong amount!"); account += amount; } int main(int argc, char **argv) { using namespace std; int debug; try { JParser<> zap("Example program to test mutex messaging."); zap['d'] = make_field(debug) = 0; zap(argc, argv); } catch(const exception &error) { FATAL(error.what() << endl); } JMutex mutex; int credit_card = 0; cout << "Trying to deposit 1000 eur\n"; { JMutex::JScopedLock lock(mutex); deposit(credit_card, 1000); } cout << "Trying to put a negative amount\n"; try { JMutex::JScopedLock lock(mutex); deposit(credit_card, -200); } catch (runtime_error const& e) { cout << e.what() << '\n'; } cout << "Let the wife do shopping\n"; try { while (credit_card) { JMutex::JScopedLock lock(mutex); int const cost = rand() % 100; cout << "Paying " << cost << "for something\n"; withdraw(credit_card, cost); } } catch (runtime_error const& e) { cout << e.what() << '\n'; } }