【Python】python 生产/消费模型

import queue
import threading
import time


def produce(q: queue.Queue):
    thread_name = threading.current_thread().getName()
    for i in range(10):
        print("生产者[%s]--- %d" % (thread_name, i))
        q.put(i, block=True)
        time.sleep(1)


def consume(q: queue.Queue):
    thread_name = threading.current_thread().getName()
    while True:
        print("消费者[%s]--- %d" % (thread_name, q.get(block=True)))
        time.sleep(2)


if __name__ == '__main__':
    q = queue.Queue(3)

    p = threading.Thread(target=produce, args=(q,), name="worker-p")
    c = threading.Thread(target=consume, args=(q,), name="worker-c")

    p.start()
    c.start()
    p.join()
    c.join()
“年轻时,我没受过多少系统教育,但什么书都读。读得最多的是诗,包括烂诗,我坚信烂诗早晚会让我邂逅好诗。” by. 马尔克斯
原文地址:https://www.cnblogs.com/jzsg/p/11151295.html