ev3dev-lang-python icon indicating copy to clipboard operation
ev3dev-lang-python copied to clipboard

Always add some form of sleep in while True loops

Open dlech opened this issue 5 years ago • 1 comments

Running a while True loop without anything in the loop to make the thread sleep will cause Python to use 100% CPU.

Since ev3dev-stretch R3, this is especially noticeable since the user program is run with higher priority (nice -10) and it will starve the rest of the operating system that is running at a lower priority. This has side-effects like making the stop button in the ev3dev VS Code extension slow to respond.

The added sleep can be time.sleep() or anything that does a blocking wait for at least a millisecond or two (poll() with timeout, waiting for a sound to finish playing, etc.).

Example programs, such as this one from the README should be modified similar to this:

ts = TouchSensor()
leds = Leds()

print("Press the touch sensor to change the LED color!")

while True:
    if ts.is_pressed:
        leds.set_color("LEFT", "GREEN")
        leds.set_color("RIGHT", "GREEN")
    else:
        leds.set_color("LEFT", "RED")
        leds.set_color("RIGHT", "RED")
    # don't use 100% CPU
    time.sleep(0.01)

dlech avatar Jul 31 '20 15:07 dlech

Thanks for the PR! I'll self-assign this to validate that the library itself has sleeps in similar loops.

WasabiFan avatar Aug 01 '20 20:08 WasabiFan