【问题标题】:Python PyQT/PySide QThread limitingPython PyQT/PySide QThread 限制
【发布时间】:2014-03-25 04:12:31
【问题描述】:

我有线程限制的问题。我想用 QThread 来做。所以 SpiderThread 是爬取一些 url 的 QThread 对象。但我想一次将工作线程限制为 X 个线程。我之前已经使用线程池和 QRunnable 完成了它,但是当 url 的数量很大时,它在 pyside 中存在问题。所以我有这个简单的代码:

 self.threads = []
    for url in self.urls:
        th = SpiderThread(url)
        th.updateresultsSignal.connect(self.update_results)
        self.threads.append(th)
        th.start()

有人有使用 QThread 限制线程的工作示例吗?

【问题讨论】:

    标签: python multithreading pyqt pyside qthread


    【解决方案1】:

    所以您希望在任何给定时间最多运行 X 个线程?那么 10 个线程共享一个 URL 队列怎么样:

    self.threads = []
    queueu = Queue(self.urls) # replace with a sync queue
    for i in xrange(1,10):
        th = SpiderThread(queue)
        th.updateresultsSignal.connect(self.update_results)
        self.threads.append(th)
        th.start()
    

    然后在每个线程的运行中,线程从队列中获取一个 URL(因此将其从队列中删除),当它处理完 URL 时,它会获取一个新的 URL。在伪代码中:

    class SpiderThread(Thread):
        def __init__(self, queue):
            self.queue = queue
        def run(self):
            while not self.queue.empty():
                maxWait = 100 # miliseconds
                try: 
                    url = self.queue.get(true, maxWait)
                    process(url)
                except Queue.Empty:
                    break # no more URLs, work completed!
    

    【讨论】:

    • 对不起,这个例子对我来说太乱了。您是指将所有 url 添加到 Queue 然后 url = queue.get() (不是 pop)还是您的意思是使用 list 然后 pop。我认为这将导致 url 被处理 10 次 - 每个线程一次,而不是 10 个线程 1 次。
    • 好的 nvm,我完成了这项工作。我会测试一段时间谢谢。
    • 您必须将每个 url 从队列中弹出,否则其他线程将处理相同的 URL。我已经为正确的方法名称等清理了示例。
    猜你喜欢
    • 1970-01-01
    • 2021-03-24
    • 2015-06-20
    • 2018-03-09
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多