Funky sort routine to demonstrate Python's threading basics.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | from threading import Thread
import time
def worker(n, emit):
time.sleep(n)
emit(n)
print(n)
def sleep_sort(s):
# Idea inspired by: http://dis.4chan.org/read/prog/1295544154
result = []
emit = result.append
threads = [Thread(target=worker, args=(x, emit)) for x in s]
for t in threads:
t.start()
for t in threads:
t.join()
return result
if __name__ == '__main__':
import random
s = list(range(10))
random.shuffle(s)
print ('Shuffled:', s)
print ('Sorted:', sleep_sort(s))
|
This fun, but impractical little recipe serves as a quick demo of Python threading basics.
As an exercise, overcome the race condition by adding absolute times and/or using semaphores or other interthread coordination.
Very nice. I would suggest to replace line 23 by
so that it is compatible with Python 3.
Recipe 577758 is an implementation using processes.
I wrote another implementation using threading.Timer: http://code.activestate.com/recipes/577762-sleepsort-timer-version/