Skip to content

Commit 24d09bd

Browse files
committed
Add bank_account_using_mutex_locks
1 parent 777370b commit 24d09bd

File tree

3 files changed

+37
-1
lines changed

3 files changed

+37
-1
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
assemble_teams_using_latch
2+
bank_account_using_mutex_locks

Makefile

+5-1
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,14 @@ SRC = $(wildcard *.cc)
55
BIN = $(SRC:.cc=)
66

77
# Rules
8-
default: assemble_teams_using_latch
8+
default: assemble_teams_using_latch bank_account_using_mutex_locks
99

1010
assemble_teams_using_latch: assemble_teams_using_latch.cc
1111
$(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+
1216
clean:
1317
@$(RM) $(BIN)
1418

bank_account_using_mutex_locks.cc

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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+
}

0 commit comments

Comments
 (0)