zoukankan      html  css  js  c++  java
  • 【Rollo的Python之路】Python 条件变量同步 学习笔记 Condition

    Python 条件变量同步(Condition):

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

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

    • wait() : 条件不满足时调用,线程会释放锁并进入等待阻塞。
    • notify(): 条件创造后调用,通知 等待池激活一个线程。
    • notifyA(): 条件创造后调用,通知等待池激活所有线程。
    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()
                    lock_con.release()
                time.sleep(3)
    
    class Consumer(threading.Thread):
        def run(self):
            global L
            while True:
                lock_con.acquire()
                if len(L) == 0:
                    lock_con.wait()
                print('消费者',self.name,":Delete" + str(L(0)),L)
                del L[0]
                lock_con.release()
                time.sleep(0.001)
    
    
    if __name__ == "__main__":
    
        L = []
        lock_con = threading.Condition()
        threads = []
        for i in range(5):
            threads.append(Producer())
    
        for t in threads:
            t.start()
    
        for t in threads:
            t.join()
        print('========================')
  • 相关阅读:
    idea config 文件
    python 时间相关
    python 限定类型
    windows 创建文件夹 链接
    java 笔记
    yml 字符串换行问题
    nginx 编译安装,问题
    git readme.md 文档头部写法
    git tag 相关操作
    敏捷开发
  • 原文地址:https://www.cnblogs.com/rollost/p/10947117.html
Copyright © 2011-2022 走看看