My program has 6 threads which are running continuously after a specific time and use same target.
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.
Original code doesn't have time.sleep(0.1)
and uses almost 100% CPU, I understand that this is caused due to while true:
. But doesn't event.wait()
make thread pause/sleep?
Using time.sleep(0.1)
make CPU usage drop to 5-7% but doesn't seem nice or correct as this may impact business logic(maybe only by little). Is there any other way CPU usage can be managed?