Multithreading Python PyQT/PySide QThread限制

Multithreading Python PyQT/PySide QThread限制,multithreading,pyqt,pyside,qthread,Multithreading,Pyqt,Pyside,Qthread,我有线程限制的问题。我想用QThread来做。所以SpiderThread是QThread对象,它正在抓取一些URL。但是我想一次将工作线程限制为X个线程。我之前用threadpool和QRunnable做过,但在pyside中,当URL数量很大时,它会出现错误。我有一个简单的代码: self.threads = [] for url in self.urls: th = SpiderThread(url) th.updateresultsSignal.

我有线程限制的问题。我想用QThread来做。所以SpiderThread是QThread对象,它正在抓取一些URL。但是我想一次将工作线程限制为X个线程。我之前用threadpool和QRunnable做过,但在pyside中,当URL数量很大时,它会出现错误。我有一个简单的代码:

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

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

所以您希望在任何给定时间最多运行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。在伪代码中:


对不起,这个例子对我来说太混乱了。您是指将所有url添加到队列,然后url=Queue.get()(不是pop),还是指使用列表,然后pop。我认为URL将被处理10次——每个线程处理一次,而不是10个线程处理1次。我会测试一段时间,谢谢。你必须将每个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!