Python生产者消费者模型

import time
import queue
import threading


class ThreadProductorConsumer():

    # 初始化模型
    def __init__(self):
        # 大小为15的缓冲池,用于容纳产品
        self.q = queue.Queue(15)
        self.screen_lock = threading.Semaphore(value=1)

    def productor(self, product):
        # 生产者不停的每3秒生产一个产品
        while True:
            self.q.put(product)
            cur_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
            cur_name = threading.current_thread().name
            # print是线程不安全的,需要信号量确保没有冲突
            self.screen_lock.acquire()
            print(cur_time+"  " + cur_name + " 生产了一个产品", sep='\n')
            self.screen_lock.release()
            time.sleep(3)

    def consumer(self):
        # 消费者不停的每2秒消费一个产品
        while True:
            self.q.get()
            cur_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
            cur_name = threading.current_thread().name
            self.screen_lock.acquire()
            print(cur_time + "  " + cur_name + " 消费了一个产品", sep='\n')
            self.screen_lock.release()
            time.sleep(2)


if __name__ == "__main__":
    tpc = ThreadProductorConsumer()

    p = "product"
    # 实例化了3个生产者
    for i in range(3):
        t = threading.Thread(target=tpc.productor, args=(p,))
        t.start()

    # 实例化了6个消费者
    for j in range(6):
        v = threading.Thread(target=tpc.consumer)
        v.start()