zoukankan      html  css  js  c++  java
  • PYTHON——多线程:条件变量(Condition)

      条件变量(Condition)也是一把锁,除了同步锁的作用外,还具有在线程间通信的功能。

      有一类线程需要满足条件之后才能够继续执行,Python提供了threading.Condition 对象用于条件变量线程的支持,它除了能提供RLock()或Lock()的方法外,还提供了 wait()、notify()、notifyAll()方法。

          lock_con=threading.Condition([Lock/Rlock]): 锁是可选选项,不传人锁,对象自动创建一个RLock()。

      wait():条件不满足时调用,线程会释放锁并进入等待阻塞;

      notify():条件创造后调用,通知等待池激活一个线程;

      notifyAll():条件创造后调用,通知等待池激活所有线程。

    实例代码:

    import threading,time
    from random import randint
    
    class Producer(threading.Thread):
        def run(self):
            global L
            while True:
                val=randint(0,100)
                print('生产者',self.name,":Append"+str(val),L)
                if lock_con.acquire():
                    L.append(val)
                    lock_con.notify()   #通知消费者可以吃包子了,激活wait。
                    lock_con.release()
                time.sleep(3)
                
    class Consumer(threading.Thread):
        def run(self):
            global L
            while True:
                lock_con.acquire()  #wait阻塞后,从这里开始这行,重新获得锁。
                if len(L)==0:          #如果包子架或容器中没有包子,则等待。
                    lock_con.wait()  #wait的作用:1、释放锁;2、阻塞,等待notify通知
                print('消费者',self.name,":Delete"+str(L[0]),L)
                del L[0]
                lock_con.release()
                time.sleep(1)
    
    if __name__=="__main__":
        L=[]  #装包子的架子或容器
        lock_con=threading.Condition()  #创建一把条件同步变量的锁。
        threads=[]
        for i in range(5):
            threads.append(Producer())
        threads.append(Consumer())
        for t in threads:
            t.start()       #start了6个线程对象。
        for t in threads:
            t.join()
        print('-------xiaohuchengsi,haha----------')
  • 相关阅读:
    Mac下django简单安装配置步骤
    NuGet 使用笔记
    gulp es7配置文件
    HaProxy配置
    Java工作环境笔记
    ReactJs笔记
    架构应该解决好对象的克隆问题
    Kotlin笔记
    Scala 笔记
    spark 笔记
  • 原文地址:https://www.cnblogs.com/chenhaiming/p/9916006.html
Copyright © 2011-2022 走看看