Jpp - the software that should make you happy
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
JMutex.cc
Go to the documentation of this file.
1 #include "JLang/JMutex.hh"
2 #include <iostream>
3 #include <stdexcept>
4 #include <cstdlib>
5 
6 #include "Jeep/JParser.hh"
7 #include "Jeep/JMessage.hh"
8 
9 
10 /**
11  * \author cpellegrino
12  */
13 
14 using namespace JPP;
15 
16 void withdraw(int& account, int amount)
17 {
18  if (amount < 0)
19  throw std::runtime_error("Wrong amount!");
20 
21  if (account < amount)
22  throw std::runtime_error("Your account can't provide the requested amount!");
23 
24  account -= amount;
25 }
26 
27 void deposit(int& account, int amount)
28 {
29  if (amount < 0)
30  throw std::runtime_error("Wrong amount!");
31 
32  account += amount;
33 }
34 
35 int main(int argc, char **argv)
36 {
37  using namespace std;
38 
39  int debug;
40 
41  try {
42 
43  JParser<> zap("Example program to test mutex messaging.");
44 
45  zap['d'] = make_field(debug) = 0;
46 
47  zap(argc, argv);
48  }
49  catch(const exception &error) {
50  FATAL(error.what() << endl);
51  }
52 
53  JMutex mutex;
54  int credit_card = 0;
55 
56  cout << "Trying to deposit 1000 eur\n";
57 
58  {
59  JMutex::JScopedLock lock(mutex);
60  deposit(credit_card, 1000);
61  }
62 
63  cout << "Trying to put a negative amount\n";
64 
65  try {
66  JMutex::JScopedLock lock(mutex);
67  deposit(credit_card, -200);
68  } catch (runtime_error const& e) {
69  cout << e.what() << '\n';
70  }
71 
72  cout << "Let the wife do shopping\n";
73 
74  try {
75  while (credit_card) {
76  JMutex::JScopedLock lock(mutex);
77 
78  int const cost = rand() % 100;
79  cout << "Paying " << cost << "for something\n";
80  withdraw(credit_card, cost);
81  }
82  } catch (runtime_error const& e) {
83  cout << e.what() << '\n';
84  }
85 }
86 
Utility class to parse command line options.
Definition: JParser.hh:1500
int main(int argc, char *argv[])
Definition: Main.cc:15
void withdraw(int &account, int amount)
Definition: JMutex.cc:16
void deposit(int &account, int amount)
Definition: JMutex.cc:27
#define make_field(A,...)
macro to convert parameter to JParserTemplateElement object
Definition: JParser.hh:1961
Very basic lock facilities to be used in multithreaded programs.
int debug
debug level
Definition: JSirene.cc:63
General purpose messaging.
#define FATAL(A)
Definition: JMessage.hh:67
Utility class to parse command line options.