并发编程四(4) 线程同步

Condition

import threading
import time
def consumer(cond):
    with cond:
        print("consumer before wait")
        cond.wait() # 等待消费(相当于进程就绪状态)
        print("consumer after wait")

def producer(cond):
    with cond:
        print("producer before notifyAll")
        # cond.notify_all() # 通知所有等待cond的消费者可以消费了
        cond.notify()  # 唤醒一个等待cond的消费者
        print("producer after notifyAll")

if __name__ == '__main__':
    condition = threading.Condition()
    t1 = threading.Thread(name = "thread-1", target = consumer, args=(condition,))
    t2 = threading.Thread(name = "thread-2", target = consumer, args=(condition,))
    t3 = threading.Thread(name = "thread-3", target = producer, args=(condition,))

    t1.start()
    time.sleep(2)
    t2.start()
    time.sleep(2)
    t3.start()
更多学习笔记移步 https://www.cnblogs.com/kknote
原文地址:https://www.cnblogs.com/kknote/p/14901949.html