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

abandon_on_cancel for async functions? #2899

Open
iulian-birlica opened this issue Dec 8, 2023 · 1 comment
Open

abandon_on_cancel for async functions? #2899

iulian-birlica opened this issue Dec 8, 2023 · 1 comment

Comments

@iulian-birlica
Copy link

Hi! First, I really like working with the library! Thanks for everything.

I want to implement a timeout mechanism for some of my functions. Something like

def async function(timeout=5):
    with trio.move_on_after(timeout):
        intensive_sync_function_that_takes_20_seconds()
        intensive_sync_function_that_takes_15_seconds()
        intensive_sync_function_that_takes_30_seconds()

but I want this to be a "harder" timeout, meaning that I want to move on after about 5-6 seconds. I know about abandon_on_cancel from to_thread.run_sync, but is there anything like that for async functions? I can't call to_thread.run_sync for every function in my function.

Maybe my design is broken is some way I don't see now, so I will ask more generally: Is there a way to actually cancel a running async task in trio? How would you implement such a timeout functionality?

@TeamSpen210
Copy link
Contributor

You’ll need to make those sync functions async, and ensure they await regularly - if you don’t need to do anything, just use trio.sleep(0). The way trio cancellation works is that all async Trio functions check for cancellation first, and if so raise an exception which is caught by the with block. So you just need to repeatedly check that.

With run_sync, that doesn’t actually cancel anything because you can’t arbitrarily stop a thread. Instead it just leaves it to keep running and ignores the result. As of the latest version, you can call trio.from_thread.check_cancelled() to check if the thead has been abandoned, and raise an exception to quit in that case. So that would also work.

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

2 participants