CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!
Path: blob/master/Day16-20/code/example21.py
Views: 729
"""1多个线程竞争一个资源 - 保护临界资源 - 锁(Lock/RLock)2多个线程竞争多个资源(线程数>资源数) - 信号量(Semaphore)3多个线程的调度 - 暂停线程执行/唤醒等待中的线程 - Condition4"""5from concurrent.futures import ThreadPoolExecutor6from random import randint7from time import sleep89import threading101112class Account():13"""银行账户"""1415def __init__(self, balance=0):16self.balance = balance17lock = threading.Lock()18self.condition = threading.Condition(lock)1920def withdraw(self, money):21"""取钱"""22with self.condition:23while money > self.balance:24self.condition.wait()25new_balance = self.balance - money26sleep(0.001)27self.balance = new_balance2829def deposit(self, money):30"""存钱"""31with self.condition:32new_balance = self.balance + money33sleep(0.001)34self.balance = new_balance35self.condition.notify_all()363738def add_money(account):39while True:40money = randint(5, 10)41account.deposit(money)42print(threading.current_thread().name,43':', money, '====>', account.balance)44sleep(0.5)454647def sub_money(account):48while True:49money = randint(10, 30)50account.withdraw(money)51print(threading.current_thread().name,52':', money, '<====', account.balance)53sleep(1)545556def main():57account = Account()58with ThreadPoolExecutor(max_workers=10) as pool:59for _ in range(5):60pool.submit(add_money, account)61pool.submit(sub_money, account)626364if __name__ == '__main__':65main()666768