← index #3332PR #8932
Duplicate · high · value 2.750
QUERY · ISSUE

_thread: timeout parameter is not implemented in Lock.acquire()

openby dlechopened 2017-09-26updated 2024-08-28
py-core

https://github.com/micropython/micropython/blob/62849b7010abffb7b0a9c9875930efe7cb77519c/py/modthread.c#L69


Background:

I'm looking for a way to implement a cancelable timeout on Linux, e.g something like threading.Timer from the standard library.

Being on Linux, I'm thinking of trying a timerfd with uasyncio instead. But if implementing the timeout parameter here is not too hard, I could give it a try. It looks to be platform dependent though, so it might be beyond my capabilities.

CANDIDATE · PULL REQUEST

py/_thread: Add support for lock.acquire timeout.

closedby andrewleechopened 2022-07-20updated 2025-05-15
py-core

This working on https://github.com/micropython/micropython-lib/pull/503 I ran into the limitation that while the _thread.Lock.acquire() function supports the waitflag argument, it doesn't handle the timeout arg - while you can pass it it's silently ignored and instead blocks forever.

This PR adds support for the timeout arg. It does so in a fairly naive way I feel... but it does work.

  1. try to get lock (unblocking)
  2. if success, return True
  3. if fail, sleep 1ms
  4. if timeout expired, return False
  5. else go back to 1.

Ref: https://docs.python.org/3/library/_thread.html#thread.lock.acquire

Similarly the test is not exactly best practice, what with having a static sleep in the middle, but it does test the behaviour.

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied