Interview Questions

None of my threads seem to run: why?

Python Questions and Answers


(Continued from previous question...)

None of my threads seem to run: why?

As soon as the main thread exits, all threads are killed. Your main thread is running too quickly, giving the threads no time to do any work.

A simple fix is to add a sleep to the end of the program that's long enough for all the threads to finish:

import threading, time

def thread_task(name, n):
for i in range(n): print name, i

for i in range(10):
T = threading.Thread(target=thread_task, args=(str(i), i))
T.start()


time.sleep(10) # <----------------------------!

But now (on many platforms) the threads don't run in parallel, but appear to run sequentially, one at a time! The reason is that the OS thread scheduler doesn't start a new thread until the previous thread is blocked.

A simple fix is to add a tiny sleep to the start of the run function:

def thread_task(name, n):
time.sleep(0.001) # <---------------------!
for i in range(n): print name, i

for i in range(10):
T = threading.Thread(target=thread_task, args=(str(i), i))
T.start()

time.sleep(10)

Instead of trying to guess how long a time.sleep() delay will be enough, it's better to use some kind of semaphore mechanism. One idea is to use the Queue module to create a queue object, let each thread append a token to the queue when it finishes, and let the main thread read as many tokens from the queue as there are threads.

(Continued on next question...)

Other Interview Questions