Python队列输出显示的输出行比预期的多

2024-04-19 14:43:07 发布

您现在位置:Python中文网/ 问答频道 /正文

为了学习Python中的排队线程,我尝试了下面的Python代码(来自一个在线教程),但是我想知道为什么producer和consumer函数会有更多的输出行。我在具有i7cpu内核的Windows机器上运行了Python代码。输出位于https://pastebin.com/NaqpQTvA。还有一些问题:

  1. main函数指示管道中的maxsize=10,所以如果我们将输出中的消费者和生产者计算在内,应该有20行,如果我们将max\u workers=2乘以2,那么总共应该有大约40行输出,对吗?但我得到了300多行的输出,不知道为什么。它们是在多个cpu核上运行还是在进行其他操作

  2. 此外,使用者输出行总是显示size=1,但它们不应该显示1到10之间的值范围以反映管道大小吗

import concurrent.futures
import logging
import queue
import random
import threading
import time

def producer(queue, event):
    """Pretend we're getting a number from the network."""
    while not event.is_set():
        message = random.randint(1, 101)
        logging.info("Producer got message: %s", message)
        queue.put(message)

    logging.info("Producer received event. Exiting")

def consumer(queue, event):
    """Pretend we're saving a number in the database."""
    while not event.is_set() or not queue.empty():
        message = queue.get()
        logging.info(
            "Consumer storing message: %s (size=%d)", message, queue.qsize()
        )

    logging.info("Consumer received event. Exiting")

if __name__ == "__main__":
    format = "%(asctime)s: %(message)s"
    logging.basicConfig(format=format, level=logging.INFO,
                        datefmt="%H:%M:%S")

    pipeline = queue.Queue(maxsize=10)
    event = threading.Event()
    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
        executor.submit(producer, pipeline, event)
        executor.submit(consumer, pipeline, event)

        time.sleep(0.1)
        logging.info("Main: about to set event")
        event.set()

Tags: producer函数代码importinfoeventformatmessage
2条回答

队列大小限制了一次队列中可以包含多少内容。它不限制队列中可以通过的东西的数量

producer尽可能快地向队列添加内容。如果队列已满,queue.put将阻塞,直到有空间为止。一旦消费者从队列中取出一个项目,生产者就会添加另一个项目

类似地,consumer尽可能快地完成任务,直到事件或队列为空

要查看发生了什么,请尝试使用计数器,而不是将随机数放入队列中。或者尝试向生产者添加一个小延迟,使其运行速度比消费者慢

def producer(queue, event):
    """Pretend we're getting a number from the network."""
    message = 0
    while not event.is_set():
        logging.info("Producer sending message: %s", message)
        queue.put(message)
        message += 1 

    logging.info("Producer received event. Exiting")

你的问题是你的最大工人:

with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
        executor.submit(producer, pipeline, event)
        executor.submit(consumer, pipeline, event)

生产者填充队列,消费者清空队列,两者同时进行

尝试更改max\u workers=1,您就会明白我的意思。或者将其保留在2并注释掉execute.submit(consumer…)行,您将看到maxsize得到了遵守

相关问题 更多 >