-
Notifications
You must be signed in to change notification settings - Fork 0
/
les_37.py
42 lines (29 loc) · 1023 Bytes
/
les_37.py
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
import threading
class BankAccount:
def __init__(self):
self.balance = 1000
self.lock = threading.Lock()
def deposit(self, amount):
with self.lock:
self.balance += amount
print(f"Deposited {amount}, new balance is {self.balance}")
def withdraw(self, amount):
with self.lock:
if self.balance >= amount:
self.balance -= amount
print(f"Withdrew {amount}, new balance is {self.balance}")
else:
print("Insufficient funds")
def deposit_task(account, amount):
for _ in range(5):
account.deposit(amount)
def withdraw_task(account, amount):
for _ in range(5):
account.withdraw(amount)
account = BankAccount()
deposit_thread = threading.Thread(target=deposit_task, args=(account, 100))
withdraw_thread = threading.Thread(target=withdraw_task, args=(account, 150))
deposit_thread.start()
withdraw_thread.start()
deposit_thread.join()
withdraw_thread.join()