Python并行编程(六):线程同步之条件

本文深入探讨了Python中线程同步的Condition机制,通过生产者消费者模型详细解析了Condition对象如何实现线程间的等待与通知,确保共享资源的安全访问。

1、基本概念

      条件指的是应用程序状态的改变。其中某些线程在等待某一条件发生,其 他线程会在该条件发生的时候进行通知,一旦条件发生,线程会拿到共享资源的唯一权限。

 

2、示例代码

from threading import Thread, Condition
import time

items = []
condition = Condition()

class consumer(Thread):

    def __init__(self):
        Thread.__init__(self)

    def consume(self):
        global condition
        global items
# 消费者通过condition.acquire得到锁来修改共享资源items condition.acquire()
if len(items) == 0:
# 如果list长度为0,那么消费者就进入等待状态 condition.wait()
print("Consumer notify: no item to consume") # 不为零通过pop消费一个item items.pop() print("Consumer notify: consumed 1 item") print("Consumer notify: items to conseme are %s" %str(len(items))) # 然后消费者的状态被通知给生产者,同时共享资源释放。 condition.notify() condition.release() def run(self): for i in range(0, 20): time.sleep(2) self.consume() class producer(Thread): def __init__(self): Thread.__init__(self) def produce(self): global condition global items
# 生产获得锁,查看缓冲队列是否已满,本例为10个,如果满了,就进入等待状态,直到被唤醒。 condition.acquire()
if len(items) == 10: condition.wait() print("Producer notify: items producted are %s" %str(len(items))) print("Producer notify: stop the production!!") items.append(1) print("Producer notify: total items producted %s" %str(len(items)))
# 如果队列没有满,就生产一个item,通知状态并释放资源 condition.notify() condition.release()
def run(self): for i in range(0, 20): time.sleep(1) self.produce() if __name__ == "__main__": producer = producer() consumer = consumer() producer.start() consumer.start() producer.join() consumer.join()

      执行结果如下:

      

 

转载于:https://www.cnblogs.com/dukuan/p/9773548.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值