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/multithread5.py
Views: 729
1
"""
2
多个线程共享数据 - 没有锁的情况
3
4
Version: 0.1
5
Author: 骆昊
6
Date: 2018-03-20
7
"""
8
9
from time import sleep
10
from threading import Thread, Lock
11
12
13
class Account(object):
14
15
def __init__(self):
16
self._balance = 0
17
self._lock = Lock()
18
19
def deposit(self, money):
20
# 先获取锁才能执行后续的代码
21
self._lock.acquire()
22
try:
23
new_balance = self._balance + money
24
sleep(0.01)
25
self._balance = new_balance
26
finally:
27
# 这段代码放在finally中保证释放锁的操作一定要执行
28
self._lock.release()
29
30
@property
31
def balance(self):
32
return self._balance
33
34
35
class AddMoneyThread(Thread):
36
37
def __init__(self, account, money):
38
super().__init__()
39
self._account = account
40
self._money = money
41
42
def run(self):
43
self._account.deposit(self._money)
44
45
46
def main():
47
account = Account()
48
threads = []
49
# 创建100个存款的线程向同一个账户中存钱
50
for _ in range(100):
51
t = AddMoneyThread(account, 1)
52
threads.append(t)
53
t.start()
54
# 等所有存款的线程都执行完毕∫
55
for t in threads:
56
t.join()
57
print('账户余额为: ¥%d元' % account.balance)
58
59
60
if __name__ == '__main__':
61
main()
62
63