使用 Python 3 的 concurrent.futures
模块进行并行工作相当容易,如下所示。
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
future_to = {executor.submit(do_work, input, 60): input for input in dictionary}
for future in concurrent.futures.as_completed(future_to):
data = future.result()
在队列中插入和检索项目也非常方便。
q = queue.Queue()
for task in tasks:
q.put(task)
while not q.empty():
q.get()
我有一个脚本在后台运行以监听更新。现在,理论上假设,当这些更新到达时,我会将它们排队并使用 ThreadPoolExecutor
同时对它们进行处理。
现在,所有这些组件都单独工作,并且有意义,但我如何才能将它们一起使用呢?我不知道是否可以实时从队列中输入 ThreadPoolExecutor
工作,除非要工作的数据是预先确定的?
简而言之,我想要做的就是每秒接收 4 条消息的更新,将它们推入队列,并让我的 concurrent.futures 处理它们。如果我不这样做,那么我就会陷入一种缓慢的顺序方法。
让我们以下面 的 Python 文档中的规范示例为例:
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
for future in concurrent.futures.as_completed(future_to_url):
url = future_to_url[future]
try:
data = future.result()
except Exception as exc:
print('%r generated an exception: %s' % (url, exc))
else:
print('%r page is %d bytes' % (url, len(data)))
URLS
的列表是固定的。是否可以实时提供此列表并让工作人员在他们过来时处理它,也许出于管理目的来自队列?我对我的方法是否 真的可行 感到有点困惑?
原文由 Ali Gajani 发布,翻译遵循 CC BY-SA 4.0 许可协议
Python 文档中的 示例 已扩展为从队列中获取其工作。需要注意的一个变化是,此代码使用
concurrent.futures.wait
而不是concurrent.futures.as_completed
以允许在等待其他工作完成时开始新工作。获取每个
url
两次的输出: