【问题标题】:How to know Python Queue in full active?如何知道 Python Queue 处于完全活动状态?
【发布时间】:2016-03-13 04:41:03
【问题描述】:

我在 python3 中为多个线程使用如下代码,我在 cpu_count() 中尝试了 2、3 和 4 次线程,但我不确定是否所有这些线程都在使用,我如何检查是否有一些队列从未使用过?

queue = Queue()

for x in range(cpu_count() * 2):
    worker = DownloadWorker(queue)
    worker.daemon = True
    worker.start()

queue.join()

class DownloadWorker(Thread):
    def __init__(self, queue):
        Thread.__init__(self)
        self.queue = queue

    def run(self):
        while True:
            link, download_path = self.queue.get()
            download_link(link, download_path)
            self.queue.task_done()

def downloadImage(imageServer, imageLocal, queue):
    queue.put((imageServer, imageLocal))

【问题讨论】:

  • 在上面的代码示例中,您只有一个传递给所有工作人员的队列。DownloadWorker 类是什么样的?
  • 我修改了问题。顺便问一下,如果thread1、3、4都在等待,是不是应该接下来执行thread1?
  • 什么是self.queue.task_done,队列中的元素是如何填充的?
  • queue.task_done 是队列而不是我的。

标签: multithreading python-3.x queue


【解决方案1】:

如果您想知道您的所有线程是否都在工作,您可以在每次启动任务时打印线程名称:

from threading import Thread
from queue import Queue
import random

import time


class DownloadWorker(Thread):
    def __init__(self, queue):
        Thread.__init__(self)
        self.queue = queue

    def run(self):
        while True:
            self.queue.get()
            print('Thread: {}'.format(self.name))
            time.sleep(random.random())

queue = Queue()
for i in range(100):
    queue.put('data')

queue.task_done()

for x in range(4):
    worker = DownloadWorker(queue)
    worker.daemon = True
    worker.start()

time.sleep(10)

队列在内部使用threading.Condition 来阻止/释放调用get()threading.Condition 使用threading.Lock 的线程。来自threading.Lock的文档:

当多个线程在acquire()中阻塞等待 状态变为解锁,释放()时只有一个线程继续 调用将状态重置为解锁;哪个等待线程 收益未定义,并且可能因实现而异。

我希望这能回答这个问题。

【讨论】:

  • 就像你说的,我使用代码来记录线程名称:logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(threadName)s - %(message)s')。我发现即使线程是4或6,所有线程都被记录了,所以我想知道thread1和thread3是否正在等待,是否应该执行thread1?
  • 已编辑答案,希望这能回答您的问题。
  • 那么哪个线程不仅会按照线程创建的顺序来处理呢?
猜你喜欢
  • 2012-04-13
  • 1970-01-01
  • 1970-01-01
  • 2013-05-20
  • 2011-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-31
相关资源
最近更新 更多