我有下一个使用 ProcessPoolExecutor 的代码:它使用 function 生成随机值,run()
如果 value < 5 则返回它并打印它:
import os
import random
import threading
import time
from concurrent.futures import ProcessPoolExecutor
class Tls(threading.local):
def __init__(self) -> None:
a = 1
class Worker:
tls = Tls()
def run(self):
while (True):
val = random.randint(1, 10)
time.sleep(random.randint(1,10))
if (val < 5):
print(f"Value {val} < 5, Process: {os.getpid()}")
return val
def main ():
executor = ProcessPoolExecutor(max_workers=3)
futures = []
for _ in range(3):
worker = Worker()
future = executor.submit(worker.run)
futures.append(future)
for el in futures:
print(el.result())
if __name__ == '__main__':
main()
问题是只有在其他进程完成时才会打印值,因为Value 3 < 5, Process: 18404
在函数中打印时它会等待一段时间在 main 中打印值,因此日志如下所示:
Value 3 < 5, Process: 18404
Value 2 < 5, Process: 28056
Value 4 < 5, Process: 22180
2
4
3
事实上,我需要在生成值后立即获取并打印它们。怎么做 ?