Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from multiprocessing.dummy import Pool as ThreadPool
- from random import randint
- from time import sleep
- def increasing_sleeps():
- """Pointless function to show using your own generator"""
- for i in xrange(10):
- yield i
- def rand_sleep(max_time):
- """Takes a max sleep time and sleeps anywhere from 0 to max_time seconds"""
- sleep_time = randint(0, max_time)
- sleep(sleep_time)
- return sleep_time
- def sleep_lots():
- """Takes the output of increasing_sleeps() and send it to rand_sleep(),
- yielding the result"""
- # multiprocessing.dummy uses threads instead of processes
- # Use two threads
- pool = ThreadPool(2)
- # imap_unordered returns the results when they are ready,
- # regular imap returns them in the order sent
- for sleep_time in pool.imap_unordered(rand_sleep, increasing_sleeps()):
- yield sleep_time
- for sleep_time in sleep_lots():
- print 'Slept', sleep_time, 'seconds'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement