Stack switching: make pystate properly save and restore asyncio state #4532
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This updates
pystate.c
to save and restore the current event loop task. This allows us to stack switch out of one async task and then block for the completion of another async task.We also add
callPyObjectMaybeSuspending
which usespromisingApply
if stack switching is available and otherwise makes a normal call. We add a private keyword argument_may_syncify
tocreate_once_callable
and have the event loop use this so async tasks can stack switch. We also make the promise handles usecallPyObjectMaybeSuspending
so thatpromise.then
,promise.finally_
, etc can use stack switching.This creates the funny situation described in #4401 where a handler can stack switch only if the entrypoint was an async function. I think I can live with this.
Example
prints:
A few API considerations:
pyodide.runPythonSyncifying
? After this PR it's sufficient to usepyodide.runPythonAsync
.PyProxy.callSyncifying
? It suffices to make it anasync
function. If you have a non async function you can make an async wrapper around it (see example).syncify
and just tell people to useasyncio.run_until_complete
instead?syncify
has problems like Usingasyncio.gather()
withsyncify()
raises error #4398 which seem hard to fix.cc @rth @ryanking13 @kor0p @dom96 @garrettgu10
Checklist