1

This is my code and I am getting varied output.

import threading
import time

def th_fun(limit,sleeptime):
    print '%s' % (limit)
    print '%s number of threads are active' % (threading.activeCount())
    time.sleep(sleeptime)



if __name__ == '__main__':
    for i in range(5):
        t = threading.Thread(target = th_fun , args = (i,1))
        t.start()

Can someone tell when a thread becomes inactive? My understanding is that 5 different thread objects are created and run and as soon as time.sleeptime() is executed it becomes inactive.

3
  • What do you mean by "tell when a thread becomes inactive"? You're right that it happens right when the function finishes. But you want the program to detect that? Commented Aug 10, 2012 at 9:54
  • Dont be surprised if your print output from each thread is "mixed". Im not sure about Python, but in c/c++ its quite common that the output may be unreadable unless you somehow synchronize the output. Commented Aug 10, 2012 at 10:07
  • This PyCon talk about the GIL does a pretty good job of explaining what's going on behind the scenes when you use multithreading. Commented Aug 10, 2012 at 10:10

1 Answer 1

1

The output is varied because the order that multiple threads are executed in, and the speeds of each of them, is nondeterministic.

As soon as t.start() occurs, the function gets called with the arguments you provided. However, this is running in the background while the next thread is set up and started. Depending on the amount of time it takes to run, it might finish running before the next thread starts, or it could finish after all the other threads have started.

It might help your understanding to add the line:

    print "Finished thread %s" % limit

at the end of your function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.