Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

timeout function is not safe to use #8

Open
asiunov opened this issue Jan 16, 2025 · 0 comments
Open

timeout function is not safe to use #8

asiunov opened this issue Jan 16, 2025 · 0 comments

Comments

@asiunov
Copy link

asiunov commented Jan 16, 2025

Python is pretty unfriendly when interrupting threads from outside of threads. The problem is that the interruption may happen in a finalization block, which releases resources, e.g. releasing global locks. If this happen, the thread may become completely broken. So, in most cases such a function is a ticking bomb. E.g. check this code snippet:

finalization_completed = False
try:
  with timeout(2):
    try:
      print("main: started", flush=True)
      time.sleep(1)
      print("main: completed", flush=True)
    finally:
      print("finalization: started", flush=True)
      time.sleep(2)
      print("starting a very important finalization, e.g. a lock release", flush=True)
      finalization_completed = True
finally:
  print(f"finalization_completed={finalization_completed}", flush=True)

output:

main: started
main: completed
finalization: started
finalization_completed=False
Traceback (most recent call last):
  File "<stdin>", line 9, in <module>
  File "<stdin>", line 4, in _handle_timeout
TimeoutException: Timeout after 2 seconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant