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/Day16-20/code/example21.py
Views: 729
1
"""
2
多个线程竞争一个资源 - 保护临界资源 - 锁(Lock/RLock)
3
多个线程竞争多个资源(线程数>资源数) - 信号量(Semaphore)
4
多个线程的调度 - 暂停线程执行/唤醒等待中的线程 - Condition
5
"""
6
from concurrent.futures import ThreadPoolExecutor
7
from random import randint
8
from time import sleep
9
10
import threading
11
12
13
class Account():
14
"""银行账户"""
15
16
def __init__(self, balance=0):
17
self.balance = balance
18
lock = threading.Lock()
19
self.condition = threading.Condition(lock)
20
21
def withdraw(self, money):
22
"""取钱"""
23
with self.condition:
24
while money > self.balance:
25
self.condition.wait()
26
new_balance = self.balance - money
27
sleep(0.001)
28
self.balance = new_balance
29
30
def deposit(self, money):
31
"""存钱"""
32
with self.condition:
33
new_balance = self.balance + money
34
sleep(0.001)
35
self.balance = new_balance
36
self.condition.notify_all()
37
38
39
def add_money(account):
40
while True:
41
money = randint(5, 10)
42
account.deposit(money)
43
print(threading.current_thread().name,
44
':', money, '====>', account.balance)
45
sleep(0.5)
46
47
48
def sub_money(account):
49
while True:
50
money = randint(10, 30)
51
account.withdraw(money)
52
print(threading.current_thread().name,
53
':', money, '<====', account.balance)
54
sleep(1)
55
56
57
def main():
58
account = Account()
59
with ThreadPoolExecutor(max_workers=10) as pool:
60
for _ in range(5):
61
pool.submit(add_money, account)
62
pool.submit(sub_money, account)
63
64
65
if __name__ == '__main__':
66
main()
67
68