Advertisement
Guest User

Untitled

a guest
Dec 15th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. from multiprocessing import Pool, TimeoutError
  2. import time
  3. import os
  4.  
  5. def f(x):
  6. print "ABBA"
  7. return x*x
  8.  
  9. if __name__ == '__main__':
  10. pool = Pool(processes=4) # start 4 worker processes
  11.  
  12. # print "[0, 1, 4,..., 81]"
  13. print pool.map(f, range(10))
  14.  
  15. # print same numbers in arbitrary order
  16. for i in pool.imap_unordered(f, range(10)):
  17. print i
  18.  
  19. # evaluate "f(20)" asynchronously
  20. res = pool.apply_async(f, (20,)) # runs in *only* one process
  21. print res.get(timeout=1) # prints "400"
  22.  
  23. # evaluate "os.getpid()" asynchronously
  24. res = pool.apply_async(os.getpid, ()) # runs in *only* one process
  25. print res.get(timeout=1) # prints the PID of that process
  26.  
  27. # launching multiple evaluations asynchronously *may* use more processes
  28. multiple_results = [pool.apply_async(os.getpid, ()) for i in range(4)]
  29. print [res.get(timeout=1) for res in multiple_results]
  30.  
  31. # make a single worker sleep for 10 secs
  32. res = pool.apply_async(time.sleep, (10,))
  33. try:
  34. print res.get(timeout=1)
  35. except TimeoutError:
  36. print "We lacked patience and got a multiprocessing.TimeoutError"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement