python多线程同步机制condition
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python多线程同步机制condition相关的知识,希望对你有一定的参考价值。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import threading
import time
def customer(cond):
t = threading.currentThread()
with cond:
# wait()方法创建了一个名为waiter的锁,并且设置锁的状态为locked。这个waiter锁用于线程间的通讯
cond.wait()
print ‘{}: Resource is available to consumer‘.format(t.name)
def producer(cond):
t = threading.currentThread()
with cond:
print ‘{}: Making resource available‘.format(t.name)
cond.notifyAll()
if __name__ == "__main__":
cond = threading.Condition()
c1 = threading.Thread(target=customer, args=(cond,), name=‘c1‘)
c2 = threading.Thread(target=customer, args=(cond,), name=‘c2‘)
p1 = threading.Thread(target=producer, args=(cond,), name=‘p1‘)
c1.start()
c2.start()
p1.start()
print ‘Main end‘
以上是关于python多线程同步机制condition的主要内容,如果未能解决你的问题,请参考以下文章
Python线程同步机制: Locks, RLocks, Semaphores, Conditions, Events和Queues