Threading Example in Python

Running multiple threads in Python is actually quite simple:

import threading
def print_items(items, thread_name=None):
    print "Thread %s started..." % thread_name
    print items
    print "Thread %s ended..." % thread_name
for i in xrange(10):
    items = range(10)
    # Create a new thread which will run print_items, passing in args and kwargs. Starts immediately.
    threading.Thread(target=print_items, args=[items], kwargs={'thread_name': i}).start()
ramins-Mac-Pro:~ ramin$ python threading_example.py
Thread 0 started...
[Thread 1 started...
[Thread 2 started...
00, , 1, 1, [0Thread 3 started...
, 22, 3[0Thread 4 started...
, , 3[0, 1, 14Thread 5 started...
, 41, , , , 52, 3, 4, , 5[0, 56, , 67, , 7, , 22, Thread 6 started...
8, 1, 6, 3[08, 3, , 4, 42, , 59, 3, 46, 7, , Thread 7 started...
]
, 597, 6]
[0, , 8, , 85, , 6Thread 1 ended...Thread 0 ended..., 9, Thread 8 started...
]
9]
1, Thread 3 ended...1
, , 2, Thread 2 ended...2
, 3[0
7, 7, 3, 48, 9], ,
, 15, 46, 7, Thread 4 ended...8
, , 28, 3, , 4, , 55, 9],
6, 9Thread 6 ended...
7, 8, 9]6
, 7]
, 8 Thread 9 started...
Thread 5 ended...
, Thread 7 ended...
9][0,
Thread 8 ended...1, 2, 3, 4
, 5, 6, 7, 8, 9]
Thread 9 ended...
ramins-Mac-Pro:~ ramin$