Python Event.wait() taking high CPU



我的程序有6个线程,它们在特定时间后连续运行,并使用相同的目标。

running = True
thread_event = Event()
def process(obj, source, *args):
global running
try:
while running:
obj(*args)
thread_event.wait(get_interval(source))      # get_interval returns time ranging from 5 seconds to 24 hours based on source
time.sleep(0.1)             # Adding this line reduces CPU usage from 90-100% to 5-7%
except Exception:
log.exception("An exception has been raised, closing all processes.")
running = False
# notify all wait(s) so they exit immediately
thread_event.set()
thread_event.clear()
def main():
thread_cdtn = Thread(target=process, name='clean_dead_tokens', args=(clean_dead_tokens, 'clean_dead_tokens'))  # One example of thread.
thread_cdtn.start()                    # Start thread here.
#  other threads start here.

原始代码没有time.sleep(0.1),并且使用几乎100%的CPU,我知道这是由while true:引起的。但是event.wait()不会使线程暂停/休眠吗?使用time.sleep(0.1)会使CPU使用率降至5-7%,但这似乎并不好或正确,因为这可能会影响业务逻辑(可能只是一点点(。是否有其他方法可以管理CPU使用情况?

这将是的最佳解释

https://stackoverflow.com/a/29082411/13837927

对于

是否有其他方法可以管理CPU使用情况?

也许它只是sleep。哈哈:-(

最新更新