最佳答案
我想在我的多线程 Python 应用程序中定期执行一个操作。我见过两种不同的做法
exit = False
def thread_func():
while not exit:
action()
time.sleep(DELAY)
或者
exit_flag = threading.Event()
def thread_func():
while not exit_flag.wait(timeout=DELAY):
action()
一种方式比另一种方式有优势吗?是使用更少的资源,还是更好地使用其他线程和 GIL?哪一个使我的应用程序中剩余的线程响应更快?
(假设某些外部事件设置为 exit
或 exit_flag
,并且我愿意在关闭时等待完全延迟)