Skip to content

Instantly share code, notes, and snippets.

@antoncohen
Created October 24, 2016 00:51
Show Gist options
  • Save antoncohen/e5dacc150ec6c03de6ff6a90d57a0a85 to your computer and use it in GitHub Desktop.
Save antoncohen/e5dacc150ec6c03de6ff6a90d57a0a85 to your computer and use it in GitHub Desktop.
sleep_lots.py
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'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment