Manoj
Manoj

Reputation: 971

Multithreading in python: when does a thread become inactive?

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.

Upvotes: 1

Views: 1266

Answers (1)

David Robinson
David Robinson

Reputation: 78610

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.

Upvotes: 1

Related Questions