关于线程同步中的条件机制

items = []
condition = threading.Condition()

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

    def consume(self):
        global condition
        global items
        # 对于消费者来说, 是使用生产者生产的东西进行消费的,需要上锁,防止其他程序使用
        condition.acquire()
        # 条件:如果items为空的话,其处于等待状态
        if len(items) == 0:
            condition.wait()
            print("Consumer notify: no item to consume")
        items.pop()
        print("Consumer notify: consumer 1 item")
        print("Consumer notify: item to consume are " + str(len(items)))
        condition.notify()
        # 消费之后释放锁
        condition.release()

    def run(self):
        for i in range(20):
            # 定义十秒钟消费一次
            time.sleep(10)
            self.consume()

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

    def produce(self):
        global condition
        global items
        condition.acquire()
        # 条件:列表里最多放10个元素
        if len(items) == 10:
            condition.wait()
            print("Producer notify: items produced are" + str(len(items)))
            print("Producer notify: stop the production!!")
        # 生产元素,供消费者消费
        items.append(1)
        print("Producer notify: total items producted " + str(len(items)))
        condition.notify()
        condition.release()
    def run(self):
        for i in range(20):
            # 5秒钟生产一次
            time.sleep(5)
            self.produce()
if __name__ == '__main__':
    producer = producer()
    consumer = consumer()
    producer.start()
    consumer.start()
    producer.join()
    consumer.join()

生产者是开启的一个线程,消费者是开启的另一个线程,对于消费者来说是10秒钟消费一次,而生产者是5秒钟生产一次,因此生产者生产的东西是足够消费者消费的,所以生产者生产结束之后消费者依然可以消费剩下的东西,而不必处于等待状态。

当生产者生产出来的东西满足消费者使用时,生产者会通知消费者可以使用该资源,这个时候消费者就会获取锁以供对共享资源的独占访问,同理,消费者消费资源之后,会通知生产者资源以及使用完毕,若生产者不生产资源的话,消费者将持续处于等待状态。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值