Advertisement
Guest User

Untitled

a guest
Oct 24th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. from multiprocessing.dummy import Pool as ThreadPool
  2. from random import randint
  3. from time import sleep
  4.  
  5.  
  6. def increasing_sleeps():
  7. """Pointless function to show using your own generator"""
  8.  
  9. for i in xrange(10):
  10. yield i
  11.  
  12.  
  13. def rand_sleep(max_time):
  14. """Takes a max sleep time and sleeps anywhere from 0 to max_time seconds"""
  15.  
  16. sleep_time = randint(0, max_time)
  17. sleep(sleep_time)
  18. return sleep_time
  19.  
  20.  
  21. def sleep_lots():
  22. """Takes the output of increasing_sleeps() and send it to rand_sleep(),
  23. yielding the result"""
  24.  
  25. # multiprocessing.dummy uses threads instead of processes
  26. # Use two threads
  27. pool = ThreadPool(2)
  28. # imap_unordered returns the results when they are ready,
  29. # regular imap returns them in the order sent
  30. for sleep_time in pool.imap_unordered(rand_sleep, increasing_sleeps()):
  31. yield sleep_time
  32.  
  33.  
  34. for sleep_time in sleep_lots():
  35. print 'Slept', sleep_time, 'seconds'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement