2019-08-09 python threading.condition

https://blog.csdn.net/brucewong0516/article/details/84587522

Condition的处理流程如下:

    首先acquire一个条件变量,然后判断一些条件。
    如果条件不满足则wait;
    如果条件满足,进行一些处理改变条件后,通过notify方法通知其他线程,其他处于wait状态的线程接到通知后会重新判断条件。
    不断的重复这一过程,从而解决复杂的同步问题。

Condition的基本原理如下:

可以认为Condition对象维护了一个锁(Lock/RLock)和一个waiting池。线程通过acquire获得Condition对象,当调用wait方法时,线程会释放Condition内部的锁并进入blocked状态,同时在waiting池中记录这个线程。当调用notify方法时,Condition对象会从waiting池中挑选一个线程,通知其调用acquire方法尝试取到锁。

Condition对象的构造函数可以接受一个Lock/RLock对象作为参数,如果没有指定,则Condition对象会在内部自行创建一个RLock。

除了notify方法外,Condition对象还提供了notifyAll方法,可以通知waiting池中的所有线程尝试acquire内部锁。由于上述机制,处于waiting状态的线程只能通过notify方法唤醒,所以notifyAll的作用在于防止有的线程永远处于沉默状态。


import threading
import time

task = []

class Producer(threading.Thread):   # 创建threading.Thread的子类来包装一个线程对象
    def run(self):
        while True:
          #print(self.name + " start")
          if con.acquire():
             print(self.name + " producer role")
             if len(task) >200:
                 con.notify()
                 con.wait()
                 print("1 $$$$$$$$")
             else:
                 for i in range(100):
                     task.append(i)
                 msg = self.name+' produce 100, count=' + str(len(task))
                 print(msg)
                 #time.sleep(2)
                 con.release()

class Consumer(threading.Thread):
   def run(self):
       while True:
           #print(self.name + " start")
           if con.acquire():
               print(self.name + " consumer role")
               if len(task) < 100:
                   con.notify()
                   con.wait()
                   print("2 $$$$$$$$")
               else:
                   for i in range(50):
                       task.pop()
                   msg = self.name+' consume 3, count='+str(len(task))
                   print(msg)
                   #time.sleep(2)
                   con.release()

con = threading.Condition()

def test():
    for i in range(5):
        c = Consumer()
        c.start()
    for i in range(2):
        p = Producer()
        p.start()
if __name__ == '__main__':
    test()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值