gpt4 book ai didi

Python线程越来越多地生成任务并消耗过多的内存和cpu

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:38:26 25 4
gpt4 key购买 nike

我有一个包含特定任务的文件,我需要每 1 秒运行一次。我编写了下面的程序并将此文件作为 linux 中的服务。当我启动服务时,python 线程生成的任务越来越多,消耗了太多的 CPU 和内存。因为linux中的最大任务数是有限制的,当任务总数超过最大值后,服务就会崩溃

As you see in this picture, the number of tasks increasing by time and very high memory and CPU usage!!!

My Service Info

threads = []
def process():
t = threading.Timer(interval=1, function=process)
t.start()
threads.append(t)
do_task()

if __name__ == '__main__':
process()

for thd in threads:
thd.join()

我的问题:如何限制我的话题?如何确保在其他任务运行之前没有新任务生成?

最佳答案

你在那里写的看起来像一个fork bomb或者至少非常非常接近它

您的 process 函数不断生成在其中运行相同函数的线程,然后才运行它应该运行的实际作业。这意味着您最终会在很短的时间内拥有大量线程。朝正确方向快速解决的方法是先完成工作,然后生成另一个线程,如下所示:

def process():
do_task()
t = threading.Timer(interval=1, function=process)
t.start()
threads.append(t)

这里要注意的重要一点是 do_task() 在创建任何其他线程之前执行

话虽这么说,为什么您需要一个额外的线程来完成手头的工作而不满足于 time.sleep

import time
while True:
time.sleep(1)
do_work()

虽然这不能保证您每秒准确完成一次工作,但您的内存占用量是恒定的,如果工作花费的时间太长,您也不会耗尽资源

关于Python线程越来越多地生成任务并消耗过多的内存和cpu,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45754548/

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