MST

星途 面试题库

面试题:Python 中 Queue/queue 模块在多线程应用的基础使用

在 Python 多线程编程中,使用 Queue/queue 模块实现一个简单的生产者 - 消费者模型。生产者线程生成 1 到 100 的整数并放入队列,消费者线程从队列中取出整数并打印,最后确保主线程等待所有线程完成。请写出完整代码。
23.6万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import threading
import queue
import time


def producer(q):
    for i in range(1, 101):
        q.put(i)
        time.sleep(0.01)


def consumer(q):
    while True:
        item = q.get()
        if item is None:
            break
        print(item)
        time.sleep(0.01)


if __name__ == '__main__':
    q = queue.Queue()
    producer_thread = threading.Thread(target=producer, args=(q,))
    consumer_thread = threading.Thread(target=consumer, args=(q,))

    producer_thread.start()
    consumer_thread.start()

    producer_thread.join()
    q.put(None)  # 发送结束信号
    consumer_thread.join()