Multithreading in python: when does a thread become inactive?

谁说我不能喝 提交于 2019-12-11 10:59:59

问题


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.


回答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.



来源:https://stackoverflow.com/questions/11899224/multithreading-in-python-when-does-a-thread-become-inactive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!