File tree 3 files changed +37
-1
lines changed
3 files changed +37
-1
lines changed Original file line number Diff line number Diff line change 1
1
assemble_teams_using_latch
2
+ bank_account_using_mutex_locks
Original file line number Diff line number Diff line change @@ -5,10 +5,14 @@ SRC = $(wildcard *.cc)
5
5
BIN = $(SRC:.cc= )
6
6
7
7
# Rules
8
- default : assemble_teams_using_latch
8
+ default : assemble_teams_using_latch bank_account_using_mutex_locks
9
9
10
10
assemble_teams_using_latch : assemble_teams_using_latch.cc
11
11
$(CXX ) $(CXXFLAGS ) -o assemble_teams_using_latch assemble_teams_using_latch.cc
12
+
13
+ bank_account_using_mutex_locks : bank_account_using_mutex_locks.cc
14
+ $(CXX ) $(CXXFLAGS ) -o bank_account_using_mutex_locks bank_account_using_mutex_locks.cc
15
+
12
16
clean :
13
17
@$(RM ) $(BIN )
14
18
Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+ #include < thread>
3
+ #include < mutex>
4
+
5
+ std::mutex accountMutex;
6
+ int balance = 500 ;
7
+
8
+ void withdraw (int amount, const std::string& user) {
9
+ std::unique_lock<std::mutex> lock (accountMutex, std::defer_lock);
10
+
11
+ // Check balance before locking
12
+ if (balance >= amount) {
13
+ // Lock now, after condition is checked
14
+ lock.lock ();
15
+ balance -= amount;
16
+ std::cout << user << " successfully withdrew $" << amount << " . Remaining balance: $" << balance << std::endl;
17
+ lock.unlock (); // Can unlock manually
18
+ } else {
19
+ std::cout << user << " attempted to withdraw $" << amount << " , but insufficient funds." << std::endl;
20
+ }
21
+ }
22
+
23
+ int main () {
24
+ std::thread userA (withdraw, 100 , " User A" );
25
+ std::thread userB (withdraw, 100 , " User B" );
26
+
27
+ userA.join ();
28
+ userB.join ();
29
+
30
+ return 0 ;
31
+ }
You can’t perform that action at this time.
0 commit comments