gpt4 book ai didi

python - Python 中的计时器对象

转载 作者:行者123 更新时间:2023-12-01 04:48:47 25 4
gpt4 key购买 nike

我有一个关于 Python 中 Timer 对象的问题: https://docs.python.org/2/library/threading.html#timer-objects

该对象基本上是一个线程,它在用户定义的秒数后调用特定函数。我的问题是:函数调用后,Thread对象自动从程序中消除,还是这个对象一直运行,消耗内存?

这段代码显示了我在说什么:

from threading import Timer
from random import randint

def call_function(x):
print "Timer number " + str(x) + " hit call function!"

for x in range(200000):
#memory used: 700.000 K
print "Creating timer number: " + str(x)
Timer(randint(1, 10), call_function, [x]).start()

在 200.000 个线程 Timer 创建并在 10 秒内被调用之后(在这次调用之后,它们应该死掉,释放空间,对吧?),程序结束执行时消耗了 700.000 K 的内存,几乎 1 GB 。

谢谢

最佳答案

计时器只是一个Thread subclass (由名为 Timer 的工厂函数创建),具有简单的 run 方法:

class _Timer(Thread):
def __init__(self, interval, function, args=[], kwargs={}):
Thread.__init__(self)
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.finished = Event()

def cancel(self):
self.finished.set()

def run(self):
self.finished.wait(self.interval)
if not self.finished.is_set():
self.function(*self.args, **self.kwargs)
self.finished.set()

线程在run()方法终止后立即终止:

Once the thread’s activity is started, the thread is considered ‘alive’. It stops being alive when its run() method terminates – either normally, or by raising an unhandled exception. The is_alive() method tests whether the thread is alive.

如果以后不再使用,计时器类对象本身应该被自动垃圾回收。

而且你无法启动 200000 个线程,这太多了(_Timer 对象将被创建,但线程不会启动)。检查这个问题:How many threads is too many?

关于python - Python 中的计时器对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28856352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com