circuitpython: try_lock() timeout

I find the widely used

while not i2c.try_lock(): pass

construct problematic (or even catastrophic in boot.py) because it will just get the code into an endless loop if try_lock() is unsuccessful. It would be nice to have an optional timeout argument so that an exception will be raised if the lock cannot be acquired within a certain timeframe. Currently, I would even opt for the timeout to have a default value of maybe 1 or 2 seconds.

About this issue

  • Original URL
  • State: closed
  • Created 6 months ago
  • Comments: 20 (2 by maintainers)

Most upvoted comments

Much of the core is still over my head so it’s dangerous for me to make conclusions after looking at the C code, but when I look at the common_hal_busio_i2c_try_lock function (rp2040), it doesn’t look to me like there is any advantage to calling the try_lock function a second time if the first call returns a False. Is it possible the while loop was used in the examples because in the limited context of the example there was no difference between infinite looping and simply exiting the code?

The loop makes sense when there is a display on the same bus that is updated in the background, and may lock the bus temporarily while that happens. There was also some discussion about adding support for gpio expanders to libraries like keypad, which would result in a similar situation - the bus becoming locked temporarily in the background, independent from your own program.

web interface for custom builds

#7594

@bludin I’m afraid that the day when we drop the support for the smallest boards is closer.

Following on @RetiredWizard’s examples, the simplest might be:

if not i2c.try_lock():
    raise RuntimeError()