-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay2.py
More file actions
93 lines (78 loc) · 2.74 KB
/
Day2.py
File metadata and controls
93 lines (78 loc) · 2.74 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
#Design a Thread-Safe Wallet System with O(1) operations
import threading
class Account:
def __init__(self,balance=0):
self.balance=balance
self.lock=threading.Lock()
class WalletSystem:
def __init__(self):
self.users={}
self.lock=threading.Lock()
def createUser(self,username,balance):
with self.lock:
if username in self.users:
return "User already exists"
self.users[username]=Account(balance)
return "User created successfully"
def getBalance(self,username):
account=self.getAccount(username)
return account.balance
def credit(self,username,amount):
with self.lock:
if username not in self.users:
return "User not found"
self.users[username].balance+=amount
return "Amount credited successfully"
def debit(self,username,amount):
with self.lock:
if username not in self.users:
return "User not found"
if self.users[username].balance<amount:
return "Insufficient balance"
self.users[username].balance-=amount
return "Amount debited successfully"
def transfer(self,from_user,to_user,amount):
account1=self.getAccount(from_user)
account2=self.getAccount(to_user)
if account1.balance<amount:
return "Insufficient balance"
account1.balance-=amount
account2.balance+=amount
return "Amount transferred successfully"
def getAccount(self,username):
with self.lock:
if username not in self.users:
return "User not found"
return self.users[username]
def test1():
wallet=WalletSystem()
wallet.createUser("Krishna",100)
def debit50():
print("Debit:",wallet.debit("Krishna",50))
def debit70():
print("Debit:",wallet.debit("Krishna",70))
t1=threading.Thread(target=debit50)
t2=threading.Thread(target=debit70)
t1.start()
t2.start()
t1.join()
t2.join()
print("Final balance:",wallet.getBalance("Krishna"))
def test2():
wallet=WalletSystem()
wallet.createUser("Krishna",100)
wallet.createUser("Divanshu",50)
def transfer():
print("Transfer from Krishna to Divanshu:",wallet.transfer("Krishna","Divanshu",50))
threads=[]
for i in range(5):
threads.append(threading.Thread(target=transfer))
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print("Final balance of Krishna:",wallet.getBalance("Krishna"))
print("Final balance of Divanshu:",wallet.getBalance("Divanshu"))
if __name__ == "__main__":
test1()
test2()