multiprocessing_pools.py 文件源码

python
阅读 22 收藏 0 点赞 0 评论 0

项目:Python-Misc 作者: SLongofono 项目源码 文件源码
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)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号