Python 多线程 Condition 用法

原文链接: https://my.oschina.net/u/3524921/blog/920452

Condition 接收一个 lock 参数,改参数必须为 Lock 或者 RLock 对象,默认为 RLock 对象。Condition 集成了 lock 对象的 acquire() 和 release() 方法,还提供了 wait() 、notify() 等方法。

wait(timeout=None)

调用时,释放当前 lock,使线程进入阻塞状态,直到其它线程调用 notify() 方式或超时,才被激活

###notify(n=1)

调用时,激动 n 个正在等待状态下的线程(实际测试时,改变 n 的值好像没有区别)

###代码示例 生产消费者模型

from threading import Thread, Condition


class Producer(Thread):

    def run(self):
        global goods
        while True:
            ''' 
            with con:
            相当于
            if con.acquire():
                ...             
                con.release()
            '''
            with con:
                goods += 8
                print(self.name + ' produce 8')
                # 激活 Consumer
                con.notify()
            time.sleep(1)

class Consumer(Thread):

    def run(self):
        global goods
        while True:
            with con:
                if goods < 1:
                    con.wait()
                    print('comsumer wait...')
                else:
                    goods -= 5
                    print(self.name + ' consume 5 ')
                    # 激活Producer
                    con.notify()
            time.sleep(1)

if __name__ == '__main__':
    goods = 0
    con = Condition()
    for i in range(2):
        p = Producer()
        p.start()
    for m in range(5):
        c = Consumer()
        c.start()

执行结果

Thread-1 produce 8
Thread-2 produce 8
Thread-3 consume 5
Thread-4 consume 5
Thread-5 consume 5
Thread-6 consume 5
Thread-2 produce 8
comsumer wait...
Thread-1 produce 8
comsumer wait...
Thread-7 consume 5
comsumer wait...
Thread-1 produce 8
comsumer wait...
Thread-2 produce 8
comsumer wait...

转载于:https://my.oschina.net/u/3524921/blog/920452

你可能感兴趣的:(Python 多线程 Condition 用法)