如果在多线程 python 应用程序中手动创建一个单独的线程(内部使用 time.sleep() ),这会影响性能吗?

If a separate thread(which uses time.sleep() inside) is made manually in a multi threaded python application, will that affect the performance?

import threading
import time

def scheduler():
    periodic_action() # requires distributed locking and it's enough if it only runs ONCE every 1 hour
    time.sleep(3600) # 1 hour
    threading.Thread(target=scheduler, daemon=True).start()

if __name__ == "__main__":
    threading.Thread(target=scheduler, daemon=True).start()

此代码 运行s 在具有 5 个线程 (gunicorn gthread) 的多线程环境中。 periodic_action() 将完成它的工作,即使它只 运行 一次(这就是为什么我只希望一个线程 运行 它)。我不确定这是一种好的安排方式吗?是否会总是保留一个线程用于此调度任务?我们将有效地拥有 4 个线程? GIL 对此有何表现?

在线程内使用 time.sleep() 是一种非常有效的方法,可以在执行其他操作之前让线程延迟。你可以有大量的线程来做这件事,它仍然会非常有效。

(但是,periodic_action() 将受制于 GIL,尤其是当多个线程同时唤醒时)。

此外,您不需要 scheduler() 函数启动另一个线程,它也可以像这样:

def scheduler():
    while True:
        periodic_action()
        time.sleep(3600) # 1 hour