并发编程四 线程同步
Posted 加油
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了并发编程四 线程同步相关的知识,希望对你有一定的参考价值。
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()
以上是关于并发编程四 线程同步的主要内容,如果未能解决你的问题,请参考以下文章