python高级线程编程-线程安全的数据结构(三)
导读:threading.ConditionCondition是Python中的条件变量,它可以让线程在某些条件下等待、通知和唤醒其他线程。Condition由Lock和Condition变量两部分组成。当调用Condition的wait( 方法...
threading.Condition
Condition是Python中的条件变量,它可以让线程在某些条件下等待、通知和唤醒其他线程。Condition由Lock和Condition变量两部分组成。当调用Condition的wait()方法时,线程会释放锁并进入等待状态,当其他线程调用Condition的notify()或notifyAll()方法时,等待的线程将被唤醒并重新尝试获取锁下面的示例展示了如何使用Condition来实现生产者-消费者模型:
import threading
import queue
class Producer(threading.Thread):
def __init__(self, queue, condition):
threading.Thread.__init__(self)
self.queue = queue
self.condition = condition
def run(self):
while True:
with self.condition:
if self.queue.qsize() 10:
self.queue.put(1)
print("Produced 1 item")
self.condition.notify()
else:
self.condition.wait()
class Consumer(threading.Thread):
def __init__(self, queue, condition):
threading.Thread.__init__(self)
self.queue = queue
self.condition = condition
def run(self):
while True:
with self.condition:
if self.queue.qsize() >
0:
self.queue.get()
print("Consumed 1 item")
self.condition.notify()
else:
self.condition.wait()
if __name__ == '__main__':
queue = queue.Queue()
condition = threading.Condition()
producer = Producer(queue, condition)
consumer = Consumer(queue, condition)
producer.start()
consumer.start()
producer.join()
consumer.join()
在上面的示例中,我们使用了一个Queue来作为生产者和消费者之间的共享数据结构,并使用了一个Condition来协调它们之间的交互。生产者会不断往队列中添加元素,当队列已经满时,它会等待消费者消费一些元素后再继续添加。消费者会不断从队列中取出元素,当队列为空时,它会等待生产者添加元素后再继续取出。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: python高级线程编程-线程安全的数据结构(三)
本文地址: https://pptw.com/jishu/9219.html