zoukankan      html  css  js  c++  java
  • 条件变量同步 -- Condition

    • Python提供的Condition对象提供了对复杂线程同步问题的支持。Condition被称为条件变量,除了提供与Lock类似的acquire和release方法外,还提供了wait和notify方法。线程首先acquire一个条件变量,然后判断一些条件。如果条件不满足则wait;如果条件满足,进行一些处理改变条件后,通过notify方法通知其他线程,其他处于wait状态的线程接到通知后会重新判断条件。不断的重复这一过程,从而解决复杂的同步问题。

    上图中def_A和def_B两个方法是相互依赖的,描述了A、B两个方法同步工作的过程

     

    • 生产者和消费者代码示例 -- 以下代码只有消费者依赖了生产者
    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.25)
    
    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()
        for t in threads:
            t.join()
    

     

     

  • 相关阅读:
    算法分析之最小子段求和
    算法分析之最大子段求和(二)
    算法分析之爬楼梯问题
    .net编码规则
    tensorflow mnist
    The tensorflow simplest calculate
    python opencv
    english
    opencv 图片识别
    随机概率
  • 原文地址:https://www.cnblogs.com/dongmengze/p/9578691.html
Copyright © 2011-2022 走看看