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

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()
上一篇:Kafka复习(一):基本概念、生产者、消费者


下一篇:消息队列-kafka-部署和简单调用