【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()
posted @ 2019-07-08 15:07  加州水果  阅读(228)  评论(0编辑  收藏  举报