• Python并行编程(六):线程同步之条件


    1、基本概念

          条件指的是应用程序状态的改变。其中某些线程在等待某一条件发生,其 他线程会在该条件发生的时候进行通知,一旦条件发生,线程会拿到共享资源的唯一权限。

    2、示例代码

    from threading import Thread, Condition
    import time
    
    items = []
    condition = Condition()
    
    class consumer(Thread):
    
        def __init__(self):
            Thread.__init__(self)
    
        def consume(self):
            global condition
            global items
    # 消费者通过condition.acquire得到锁来修改共享资源items condition.acquire()
    if len(items) == 0:
    # 如果list长度为0,那么消费者就进入等待状态 condition.wait()
    print("Consumer notify: no item to consume") # 不为零通过pop消费一个item items.pop() print("Consumer notify: consumed 1 item") print("Consumer notify: items to conseme are %s" %str(len(items))) # 然后消费者的状态被通知给生产者,同时共享资源释放。 condition.notify() condition.release() def run(self): for i in range(0, 20): time.sleep(2) self.consume() class producer(Thread): def __init__(self): Thread.__init__(self) def produce(self): global condition global items
    # 生产获得锁,查看缓冲队列是否已满,本例为10个,如果满了,就进入等待状态,直到被唤醒。 condition.acquire()
    if len(items) == 10: condition.wait() print("Producer notify: items producted are %s" %str(len(items))) print("Producer notify: stop the production!!") items.append(1) print("Producer notify: total items producted %s" %str(len(items)))
    # 如果队列没有满,就生产一个item,通知状态并释放资源 condition.notify() condition.release()
    def run(self): for i in range(0, 20): time.sleep(1) self.produce() if __name__ == "__main__": producer = producer() consumer = consumer() producer.start() consumer.start() producer.join() consumer.join()

          执行结果如下:

          

  • 相关阅读:
    zabbix 4.0 监控磁盘IO的实施笔记
    梅登黑德定位系统
    sdrplay sdr 支持的sample rate
    记录一下几个中移动可以PING的检测地址及部份DNS设置
    升级mariadb 10后目录权限问题的笔记
    C#单独启动进程的几种方式及使用特点(使用不当导致端口无法释放)
    SqlBulkCopy批量插入数据时,不执行触发器和约束的解决方法
    C# 处理大量数据的技巧
    C# 几种集合性能比较
    WPF学习网址整理
  • 原文地址:https://www.cnblogs.com/dukuan/p/9773548.html
Copyright © 2020-2023  润新知