ev3dev / ev3dev-lang-python

Pure python bindings for ev3dev
MIT License
429 stars 145 forks source link

Always add some form of sleep in while True loops #754

Open dlech opened 4 years ago

dlech commented 4 years ago

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)
WasabiFan commented 4 years ago

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