CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
jackfrued

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: jackfrued/Python-100-Days
Path: blob/master/Day01-15/code/Day13/test2.py
Views: 729
1
import time
2
from threading import Thread, Lock
3
4
5
class Account(object):
6
7
def __init__(self, balance=0):
8
self._balance = balance
9
self._lock = Lock()
10
11
@property
12
def balance(self):
13
return self._balance
14
15
def deposit(self, money):
16
# 当多个线程同时访问一个资源的时候 就有可能因为竞争资源导致资源的状态错误
17
# 被多个线程访问的资源我们通常称之为临界资源 对临界资源的访问需要加上保护
18
if money > 0:
19
self._lock.acquire()
20
try:
21
new_balance = self._balance + money
22
time.sleep(0.01)
23
self._balance = new_balance
24
finally:
25
self._lock.release()
26
27
28
class AddMoneyThread(Thread):
29
30
def __init__(self, account):
31
super().__init__()
32
self._account = account
33
34
def run(self):
35
self._account.deposit(1)
36
37
38
def main():
39
account = Account(1000)
40
tlist = []
41
for _ in range(100):
42
t = AddMoneyThread(account)
43
tlist.append(t)
44
t.start()
45
for t in tlist:
46
t.join()
47
print('账户余额: %d元' % account.balance)
48
49
50
if __name__ == '__main__':
51
main()
52
53