本文共 1157 字,大约阅读时间需要 3 分钟。
# -*- coding:utf-8 -*-""" Created by FizLin https://github.com/Fiz1994"""# Consume one item# with cv:# while not an_item_is_available():# cv.wait()# get_an_available_item()## # Produce one item# with cv:# make_an_item_available()# cv.notify()from threading import Thread, Conditionimport timequeue = []MAX_NUM = 10condition = Condition()def producer(): global queue while True: condition.acquire() if len(queue) <= 0: # 生产 queue.extend([i for i in range(10)]) print('生成数据,通知消费者 现在条数:', len(queue)) condition.notify() condition.wait() else: print('生产者判断现在含有的数据: 大于0 不需要再生产', len(queue)) condition.notify() condition.release() time.sleep(1)def consumer(): global queue while True: condition.acquire() if len(queue) <= 0: print('消费者无法消费到数据,处于等待状态') condition.wait() else: print('消费数据:', queue.pop(0)) time.sleep(1) condition.notify() condition.release()p = Thread(target=producer)c = Thread(target=consumer)p.start()c.start()
转载地址:http://owjko.baihongyu.com/