-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaccount.cpp
More file actions
105 lines (59 loc) · 1.63 KB
/
account.cpp
File metadata and controls
105 lines (59 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <iostream>
#include <cstdlib>
#include <vector>
#include <pthread.h>
#include <unistd.h>
using namespace std;
///----- Initialize balance and declare lock------///
long balance = 0;
pthread_mutex_t acc;
///------Define struct for transaction -----///
struct transact{
char op;
long amount;
};
///------Thread handler function---------///
void * account_op(void * v){
sleep(rand()%7); // Wait a random time to simulate delay
transact * t = (transact *)v;
pthread_mutex_lock(&acc); // aquire lock for deposit or withdraw
if(t->op == 'd')
balance += t->amount;
else
balance -= t->amount;
cout << "Current balance is " << balance << endl;
pthread_mutex_unlock(&acc); // release lock
delete t;
return 0;
}
///---------Main-----------///
int main(){
pthread_t thread;
vector<pthread_t> thread_vec; // list of thread spawned
transact * t;
long amount;
char op = 's';
pthread_mutex_init(&acc, NULL); // initialize mutex
cout << "Enter 'd' to deposit or 'w' to withdraw <space> amount involved and 'q' to quit" << endl;
while(op != 'q'){
cout << ">> ";
cin >> op;
switch(op){
case 'd': case'w': // deposit or withdraw
cin >> amount;
t = new transact;
t->op = op;
t->amount = amount;
pthread_create(&thread, NULL, account_op, (void *)t); // create thread
thread_vec.push_back(thread); // maintain list
break;
default:
break;
}
}
for(vector<pthread_t>::iterator iter = thread_vec.begin(); iter != thread_vec.end(); iter++){ // wait for all thread to finish
pthread_join(*iter,NULL);
}
pthread_mutex_destroy(&acc); // destroy lock
return 0;
}