1

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?

codingenious
  • 8,385
  • 12
  • 60
  • 90

1 Answers1

1

This will be the best explanation

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

for

Is there any other way CPU usage can be managed?

maybe it's just sleep. ahaha :-)

tomy0608
  • 317
  • 1
  • 9