python中的多线程:线程何时变为非活动状态? [英] Multithreading in python: when does a thread become inactive?

查看:107
本文介绍了python中的多线程:线程何时变为非活动状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,输出越来越多.

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()

有人可以告诉我线程何时变为非活动状态吗?我的理解是,将创建并运行5个不同的线程对象,并且一旦执行time.sleeptime(),它就会变为非活动状态.

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.

推荐答案

输出是可变的,因为执行多个线程的顺序以及每个线程的速度是不确定的.

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

t.start()发生时,该函数将使用您提供的参数进行调用.但是,在下一个线程被设置并启动时,它在后台运行.根据运行时间的长短,它可能在下一个线程启动之前完成运行,或者可能在所有其他线程启动之后完成.

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

在功能末尾.

这篇关于python中的多线程:线程何时变为非活动状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆