Python3 从队列和多个线程获取响应
因为我程序中每个模块的搜索功能需要花费很多时间,主要是因为要发送很多HTTP请求,所以我想让它们通过线程系统同时运行。等所有线程都完成后,我想把所有module.search
线程的返回值都收集到一起。
# Create threads to fasten up the search process
threads_list = list()
que = Queue(len(self.modules))
retObj = []
for index, module in enumerate(self.modules):
thread = Thread(
target=lambda q, arg1: q.put(module.search(arg1)), args=(que, title)
)
que.put(index)
threads_list.append(thread)
thread.start()
# Wait for all threads to finish
for thread in threads_list:
thread.join()
# ALl threads have finished here
result = que.get()
print(result)```
The problem is that with que.get() I only get the result of the last thread and not the result of all threads together
1 个回答
0
这一行 result = que.get()
只获取一个结果,因为它只请求了一个结果!
如果你想要获取所有的结果,可以试试这个:
results = list(que.queue)
队列的 'queue' 属性是它内部的存储容器(实际上是一个双端队列)。虽然没有详细说明,但这意味着不应该经常使用它。不过,由于你所有的线程都已经完成了对队列的写入,所以在这里使用它是相对安全的。