我遇到线程限制问题。我想用QThread来做。所以SpiderThread是QThread对象抓取一些网址。但我想一次将工作线程限制为X线程。我之前已经使用threadpool和QRunnable完成了它,但是当网址数量很大时,它在pyside中出现问题。所以我有这个简单的代码:
self.threads = []
for url in self.urls:
th = SpiderThread(url)
th.updateresultsSignal.connect(self.update_results)
self.threads.append(th)
th.start()
任何人都有使用QThread限制线程的工作示例吗?
答案 0 :(得分:2)
所以你想在任何给定时间运行最多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!