async_func
和async_func2
)。 Pool
提交给apply_async
并花费不同的时间,即我无法确定首先提交的作业是否也会完成.get(timeout=0.1)
如何检查作业是否仍在队列中等待还是已在运行?
使用Queue
正确的方式还是有更简单的方法?
import multiprocessing
import random
import time
def async_func(x):
iterations = 0
x = (x + 0.1) % 1
while (x / 10.0) - random.random() < 0:
iterations += 1
time.sleep(0.01)
return iterations
def async_func2(x):
return(async_func(x + 0.5))
if __name__ == "__main__":
results = dict()
status = dict()
finished_processes = 0
worker_pool = multiprocessing.Pool(4)
jobs = 10
for i in range(jobs):
if i % 2 == 0:
results[i] = worker_pool.apply_async(async_func, (i,))
else:
results[i] = worker_pool.apply_async(async_func2, (i,))
status[i] = 'submitted'
while finished_processes < jobs:
for i in range(jobs):
if status[i] != 'finished':
try:
print('{0}: iterations needed = {1}'.format(i, results[i].get(timeout=0.1)))
status[i] = 'finished'
finished_processes += 1
except:
# how to distinguish between "running but no result yet" and "waiting to run"
status[i] = 'unknown'
答案 0 :(得分:1)
只需将状态字典发送到函数,因为dicts是可变的,你需要做的就是更改你的函数:
def async_func2(status, x):
status[x] = 'Started'
return(async_func(x + 0.5))
当然,您可以在致电apply_async