我有一个多处理线程池,其中一个循环在主线程上运行。主循环必须在不被阻塞的情况下运行:它在启动时以及每当处理完所有结果并且必须计算新的集合时向线程池发出任务,同时检索即使池仍然繁忙时也可用的结果。
import multiprocessing as mp
def double(x):
return x * 2
pool = mp.Pool()
items = [1, 2, 3, 4]
result = None
while True:
if result:
for value in result.get():
print(value)
if not result or result.ready():
result = pool.map_async(double, items)
print("This should still execute even when results aren't ready!")
尽管每个文档都同意
map_async
应该是非阻塞的,但整个 while True
循环会等待,直到它们准备好。这似乎是由 result.get()
触发的,但如果使用 map_async
,即使这样也不应该阻塞主循环,因此为什么有一个 result.ready()
方法来检查整个任务是否已完成。是否有 result.get()
的非阻塞版本或我必须使用的其他方法?
正如其他人所证实的,似乎
result.get()
总是意味着阻塞:我的期望是,如果使用 map_async
而不是 map
result.get
方法将返回部分结果而不阻塞。需要的是 imap
或 imap_unordered
成功交付调用时完成的结果列表,而不是等到一切准备就绪。