Advertisement
Guest User

Untitled

a guest
Oct 24th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. from multiprocessing import Pool, cpu_count
  2. from random import randint
  3. from time import sleep
  4.  
  5.  
  6. class RandSleep(object):
  7. """multiprocessing.Pool.imap* needs to pickle the function it send to the
  8. processes. It can't pickle functions or instance methods. But oddly it
  9. can pickle instances of custom classes. So write the function as a
  10. callable class."""
  11.  
  12. def __call__(self, max_time):
  13. sleep_time = randint(0, max_time)
  14. sleep(sleep_time)
  15. return sleep_time, max_time
  16.  
  17.  
  18. class Sleepy(object):
  19. def increasing_sleeps(self):
  20. """Pointless function to show using your own generator"""
  21.  
  22. for i in xrange(10):
  23. yield i
  24.  
  25. def sleep_lots(self):
  26. """Takes the output of increasing_sleeps() and send it to rand_sleep(),
  27. yielding the result"""
  28.  
  29. # Use half of available cores, which is all physical cores if using
  30. # Hyper-Threading, or use one core on uniprocessor systems.
  31. cores = max(cpu_count() // 2, 1)
  32. pool = Pool(cores)
  33. rand_sleep = RandSleep()
  34. # imap_unordered returns the results when they are ready,
  35. # regular imap returns them in the order sent
  36. for sleep_time, max_time in pool.imap_unordered(rand_sleep, self.increasing_sleeps()):
  37. yield sleep_time, max_time
  38.  
  39.  
  40. sleepy = Sleepy()
  41.  
  42. for sleep_time, max_time in sleepy.sleep_lots():
  43. print 'Slept', sleep_time, 'seconds of max', max_time
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement