多线程模块的condition对象

Python提供的Condition对象提供了对复杂线程同步问题的支持。Condition被称为条件变量,除了提供与Lock相似的acquire和release方法外,还提供了wait和notify方法。函数

使用Condition的主要方式为:线程首先acquire一个条件变量,而后判断一些条件。若是条件不知足则wait;若是条件知足,进行一些处理改变条件后,经过notify方法通知其余线程,其余处于wait状态的线程接到通知后会从新判断条件。不断的重复这一过程,从而解决复杂的同步问题。
下面咱们经过很著名的“生产者-消费者”模型来来演示下,在Python中使用Condition实现复杂同步ui

import threading 
import time 
 
condition = threading.Condition() 
products = 0 
 
class Producer(threading.Thread): 
    def __init__(self): 
        threading.Thread.__init__(self) 
 
    def run(self): 
        global condition, products 
        while True: 
            if condition.acquire(): 
                if products < 10: 
                    products += 1; 
                    print "Producer(%s):deliver one, now products:%s" %(self.name, products) 
                    condition.notify() 
                else: 
                    print "Producer(%s):already 10, stop deliver, now products:%s" %(self.name, products) 
                    condition.wait(); 
                condition.release() 
                time.sleep(2) 
 
class Consumer(threading.Thread): 
    def __init__(self): 
        threading.Thread.__init__(self) 
 
    def run(self): 
        global condition, products 
        while True: 
            if condition.acquire(): 
                if products > 1: 
                    products -= 1 
                    print "Consumer(%s):consume one, now products:%s" %(self.name, products) 
                    condition.notify() 
                else: 
                    print "Consumer(%s):only 1, stop consume, products:%s" %(self.name, products) 
                    condition.wait(); 
                condition.release() 
                time.sleep(2) 
 
if __name__ == "__main__": 
    for p in range(0, 2): 
        p = Producer() 
        p.start() 
 
    for c in range(0, 10): 
        c = Consumer() 
        c.start()

另外:Condition对象的构造函数能够接受一个Lock/RLock对象做为参数,若是没有指定,则Condition对象会在内部自行建立一个RLock;除了notify方法外,Condition对象还提供了notifyAll方法,能够通知waiting池中的全部线程尝试acquire内部锁。因为上述机制,处于waiting状态的线程只能经过notify方法唤醒,因此notifyAll的做用在于防止有线程永远处于沉默状态。线程

相关文章
相关标签/搜索