Welcome, guest | Sign In | My Account | Store | Cart

Funky sort routine to demonstrate Python's threading basics.

Python, 26 lines
 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.

3 comments

Andre Roberge 12 years, 10 months ago  # | flag

Very nice. I would suggest to replace line 23 by

s = list(range(10))

so that it is compatible with Python 3.

Benjamin Peterson 12 years, 10 months ago  # | flag

Recipe 577758 is an implementation using processes.

wong2 12 years, 10 months ago  # | flag

I wrote another implementation using threading.Timer: http://code.activestate.com/recipes/577762-sleepsort-timer-version/