def pidwrapper(num):
print("Process {} starting".format(os.getpid()))
result = dowork(num)
print("Process {} ending".format(os.getpid()))
return result
if __name__ == "__main__":
# Sequential list for generating fibbonacci sequence
myList = range(30)
# Generates a pool of 30 workers
myPool = multiprocessing.Pool(processes=30)
# sets up and automatically starts a worker for each number
#output = pool.map(dowork, myList)
# sets up an automatically starts a worker for each number, returning results
# as they arrive
results = [myPool.apply_async(pidwrapper, (num,)) for num in myList]
# The get will raise an exception if the result is not ready. We can use
# this to check it and move on if the result is not ready.
done = False
visited = [0 for x in myList]
finalList = [0 for x in myList]
start = time.time()
while not done:
try:
for i in range(len(visited)):
if not visited[i]:
print("Fibonacci number: {}\n\tfinished in: {} seconds\n\tResult: {}".format(i, time.time()-start, results[i].get(timeout=1)))
visited[i] = 1
finalList[i] = results[i].get()
done = True
except multiprocessing.TimeoutError:
pass
# The result is still being computed, move on to something else.
print(finalList)
评论列表
文章目录