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/multithread6.py
Views: 729
1
"""
2
多个线程共享数据 - 有锁的情况
3
4
Version: 0.1
5
Author: 骆昊
6
Date: 2018-03-20
7
"""
8
9
import time
10
import threading
11
12
13
class Account(object):
14
15
def __init__(self):
16
self._balance = 0
17
self._lock = threading.Lock()
18
19
def deposit(self, money):
20
# 获得锁后代码才能继续执行
21
self._lock.acquire()
22
try:
23
new_balance = self._balance + money
24
time.sleep(0.01)
25
self._balance = new_balance
26
finally:
27
# 操作完成后一定要记着释放锁
28
self._lock.release()
29
30
@property
31
def balance(self):
32
return self._balance
33
34
35
if __name__ == '__main__':
36
account = Account()
37
# 创建100个存款的线程向同一个账户中存钱
38
for _ in range(100):
39
threading.Thread(target=account.deposit, args=(1,)).start()
40
# 等所有存款的线程都执行完毕
41
time.sleep(2)
42
print('账户余额为: ¥%d元' % account.balance)
43
44
# 想一想结果为什么不是我们期望的100元
45
46