我的程序有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使用吗?
发布于 2020-12-15 07:08:33
https://stackoverflow.com/questions/65247314
复制相似问题