首页 > 技术文章 > 【Python】python 生产/消费模型

jzsg 2019-07-08 15:07 原文

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()

推荐阅读