Condition 實現消費者生產者

# -*- 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, Condition
import time

queue = []
MAX_NUM = 10
condition = 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()
相關文章
相關標籤/搜索