Python 线程间同步之条件变量condition理解

python同步的条件变量主要是应对互斥锁搞不定的情况,之前一直对condition搞不太清楚,最近特地查阅了一些资料,有一些心得与大家分享。
经典例子:银行存钱取钱问题。

     from concurrent.futures import ThreadPoolExecutor
     from random import randint
     from time import sleep
     
     import threading
     
     
     class Account():
         """银行账户"""
     
         def __init__(self, balance=0):
             self.balance = balance
             lock = threading.Lock()
             self.condition = threading.Condition(lock)
     
         def withdraw(self, money):
             """取钱"""
             with self.condition:
                 while money > self.balance:
                     self.condition.wait()
                 new_balance = self.balance - money
                 sleep(0.001)
                 self.balance = new_balance
     
         def deposit(self, money):
             """存钱"""
             with self.condition:
                 new_balance = self.balance + money
                 sleep(0.001)
                 self.balance = new_balance
                 self.condition.notify_all()
     
     
     def add_money(account):
         while True:
             money = randint(5, 10)
             account.deposit(money)
             print(threading.current_thread().name, 
                   ':', money, '====>', account.balance)
             sleep(0.5)
     
     
     def sub_money(account):
         while True:
             money = randint(10, 30)
             account.withdraw(money)
             print(threading.current_thread().name, 
                   ':', money, '<====', account.balance)
             sleep(1)
     
     
     def main():
         account = Account()
         with ThreadPoolExecutor(max_workers=10) as pool:
             for _ in range(5):
                 pool.submit(add_money, account)
                 pool.submit(sub_money, account)
     
     
     if __name__ == '__main__':
         main()

这里特别要关注的是condition的执行流程,需要借助代码分析,重要的是notify()、wait()两个函数。源码如下:
Python 线程间同步之条件变量condition理解_第1张图片
进入wait()函数后:
1)先申请了一个上层锁,并放入队列中;
2)释放底层锁(condition变量申明时的锁);
3)再次申请上层锁(等待notify()释放);
4)尝试获取底层锁(两种情况,若另外的线程调用wait(),此时可获取底层锁;若另外的线程直接release(),此时获取底层锁)
Python 线程间同步之条件变量condition理解_第2张图片
notify()函数比较简单,就是释放上层锁!
回头看前面的代码就能比较好的理解线程执行过程了:
1)取钱线程获取底层锁,发现银行存款不够,调用wait(),释放底层锁,同时申请了上层锁,阻塞,等待存钱线程notify();
2)存钱线程存钱后,nofity(),释放上层锁;同时,通过release()释放底层锁;
3)取钱线程获取上层锁;获取底层锁;程序往下进行!

你可能感兴趣的:(Python 线程间同步之条件变量condition理解)