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

标签 python linux multithreading

我有一个包含特定任务的文件,我需要每 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/

相关文章:

python - 基于词典的情感分析的准确性

python - tkinter 中的 for 循环问题

linux - Teradata DBS 状态为 7 : System is operational without PEs - Sessions are not allowed

c - 获取线程最后调度的 CPU/核心

c# - 为什么临时变量可以阻止客户端删除事件处理程序?

python - 将数据帧转换为热图矩阵?

python - 在django中创建原子事务是否会自动创建锁

linux - 放弃 X 会完全伤害吗?

java - 什么是 "inline thread"?

java - Java中的多线程: field not incrementing as expected