这里有新鲜出炉的 Python3 官方中文指南,程序狗速度看过来!
Python 是一种面向对象、解释型计算机程序设计语言,由 Guido van Rossum 于 1989 年底发明,第一个公开发行版发行于 1991 年。Python 语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是 C/C++)很轻松地联结在一起。
这篇文章主要介绍了 python 条件变量之生产者与消费者操作, 结合具体实例形式分析了 Python 条件变量的概念、原理、及线程操作的相关技巧, 需要的朋友可以参考下
本文实例讲述了 python 条件变量之生产者与消费者操作。分享给大家供大家参考,具体如下:
互斥锁是最简单的线程同步机制,面对复杂线程同步问题,Python 还提供了 Condition 对象。Condition 被称为条件变量,除了提供与 Lock 类似的 acquire 和 release 方法外,还提供了 wait 和 notify 方法。线程首先 acquire 一个条件变量,然后判断一些条件。如果条件不满足则 wait;如果条件满足,进行一些处理改变条件后,通过 notify 方法通知其他线程,其他处于 wait 状态的线程接到通知后会重新判断条件。不断的重复这一过程,从而解决复杂的同步问题。
可以认为 Condition 对象维护了一个锁(Lock/RLock) 和一个 waiting 池。线程通过 acquire 获得 Condition 对象,当调用 wait 方法时,线程会释放 Condition 内部的锁并进入 blocked 状态,(但实际上不会 block 当前线程)同时在 waiting 池中记录这个线程。当调用 notify 方法时,Condition 对象会从 waiting 池中挑选一个线程,通知其调用 acquire 方法尝试取到锁。
Condition 对象的构造函数可以接受一个 Lock/RLock 对象作为参数,如果没有指定,则 Condition 对象会在内部自行创建一个 RLock。
线程同步经典问题 ---- 生产者与消费者问题可以使用条件变量轻松解决。
- import threading import time class Producer(threading.Thread) : def __init__(self) : threading.Thread.__init__(self) def run(self) : global count
- while True: con.acquire() if count < 20 : count += 1 print self.name,
- " Producer product 1,current is %d" % (count) con.notify()
- else: print self.name,
- "Producer say box is full"con.wait() con.release() time.sleep(1) class Consumer(threading.Thread) : def __init__(self) : threading.Thread.__init__(self) def run(self) : global count
- while True: con.acquire() if count > 4 : count -= 4 print self.name,
- "Consumer consume 4,current is %d" % (count) con.notify()
- else: con.wait() print self.name,
- " Consumer say box is empty"con.release() time.sleep(1) count = 0 con = threading.Condition() def test() : for i in range(1) : a = Consumer() a.start() for i in range(1) : b = Producer() b.start() if __name__ == '__main__': test()
上面的代码假定消费者消费的比较快,输出结果为:
希望本文所述对大家 Python 程序设计有所帮助。
来源: http://www.phperz.com/article/17/0710/332846.html