码迷,mamicode.com
首页 > 其他好文 > 详细

条件变量同步 -- Condition

时间:2018-09-03 15:34:03      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:read   rom   过程   其他   相互   生产者和消费者   方法   art   on()   

  • 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()

 

 

 

 

条件变量同步 -- Condition

标签:read   rom   过程   其他   相互   生产者和消费者   方法   art   on()   

原文地址:https://www.cnblogs.com/dongmengze/p/9578691.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!