-
Notifications
You must be signed in to change notification settings - Fork 783
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
feat: add #[pyo3(allow_threads)] to release the GIL in (async) functions #3610
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
Add `#[pyo3(allow_threads)]` to release the GIL in (async) functions |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -6,6 +6,7 @@ use syn::{ext::IdentExt, spanned::Spanned, Ident, Result}; | |||||
|
||||||
use crate::utils::Ctx; | ||||||
use crate::{ | ||||||
attributes, | ||||||
attributes::{FromPyWithAttribute, TextSignatureAttribute, TextSignatureAttributeValue}, | ||||||
deprecations::{Deprecation, Deprecations}, | ||||||
params::{impl_arg_params, Holders}, | ||||||
|
@@ -379,6 +380,7 @@ pub struct FnSpec<'a> { | |||||
pub asyncness: Option<syn::Token![async]>, | ||||||
pub unsafety: Option<syn::Token![unsafe]>, | ||||||
pub deprecations: Deprecations<'a>, | ||||||
pub allow_threads: Option<attributes::kw::allow_threads>, | ||||||
} | ||||||
|
||||||
pub fn parse_method_receiver(arg: &syn::FnArg) -> Result<SelfType> { | ||||||
|
@@ -416,6 +418,7 @@ impl<'a> FnSpec<'a> { | |||||
text_signature, | ||||||
name, | ||||||
signature, | ||||||
allow_threads, | ||||||
.. | ||||||
} = options; | ||||||
|
||||||
|
@@ -461,6 +464,7 @@ impl<'a> FnSpec<'a> { | |||||
asyncness: sig.asyncness, | ||||||
unsafety: sig.unsafety, | ||||||
deprecations, | ||||||
allow_threads, | ||||||
}) | ||||||
} | ||||||
|
||||||
|
@@ -603,6 +607,21 @@ impl<'a> FnSpec<'a> { | |||||
bail_spanned!(name.span() => "`cancel_handle` may only be specified once"); | ||||||
} | ||||||
} | ||||||
if let Some(FnArg::Py(py_arg)) = self | ||||||
.signature | ||||||
.arguments | ||||||
.iter() | ||||||
.find(|arg| matches!(arg, FnArg::Py(_))) | ||||||
{ | ||||||
ensure_spanned!( | ||||||
self.asyncness.is_none(), | ||||||
py_arg.ty.span() => "GIL token cannot be passed to async function" | ||||||
); | ||||||
ensure_spanned!( | ||||||
self.allow_threads.is_none(), | ||||||
py_arg.ty.span() => "GIL cannot be held in function annotated with `allow_threads`" | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Similarly here I think we want to just name the type:
Suggested change
|
||||||
); | ||||||
} | ||||||
|
||||||
if self.asyncness.is_some() { | ||||||
ensure_spanned!( | ||||||
|
@@ -612,8 +631,21 @@ impl<'a> FnSpec<'a> { | |||||
} | ||||||
|
||||||
let rust_call = |args: Vec<TokenStream>, holders: &mut Holders| { | ||||||
let mut self_arg = || self.tp.self_arg(cls, ExtractErrorMode::Raise, holders, ctx); | ||||||
|
||||||
let allow_threads = self.allow_threads.is_some(); | ||||||
let mut self_arg = || { | ||||||
let self_arg = self.tp.self_arg(cls, ExtractErrorMode::Raise, holders, ctx); | ||||||
if self_arg.is_empty() { | ||||||
self_arg | ||||||
} else { | ||||||
let self_checker = holders.push_gil_refs_checker(self_arg.span()); | ||||||
quote! { | ||||||
#pyo3_path::impl_::deprecations::inspect_type(#self_arg &#self_checker), | ||||||
} | ||||||
} | ||||||
}; | ||||||
let arg_names = (0..args.len()) | ||||||
.map(|i| format_ident!("arg_{}", i)) | ||||||
.collect::<Vec<_>>(); | ||||||
let call = if self.asyncness.is_some() { | ||||||
let throw_callback = if cancel_handle.is_some() { | ||||||
quote! { Some(__throw_callback) } | ||||||
|
@@ -625,9 +657,6 @@ impl<'a> FnSpec<'a> { | |||||
Some(cls) => quote!(Some(<#cls as #pyo3_path::PyTypeInfo>::NAME)), | ||||||
None => quote!(None), | ||||||
}; | ||||||
let arg_names = (0..args.len()) | ||||||
.map(|i| format_ident!("arg_{}", i)) | ||||||
.collect::<Vec<_>>(); | ||||||
let future = match self.tp { | ||||||
FnType::Fn(SelfType::Receiver { mutable: false, .. }) => { | ||||||
quote! {{ | ||||||
|
@@ -645,18 +674,7 @@ impl<'a> FnSpec<'a> { | |||||
} | ||||||
_ => { | ||||||
let self_arg = self_arg(); | ||||||
if self_arg.is_empty() { | ||||||
quote! { function(#(#args),*) } | ||||||
} else { | ||||||
let self_checker = holders.push_gil_refs_checker(self_arg.span()); | ||||||
quote! { | ||||||
function( | ||||||
// NB #self_arg includes a comma, so none inserted here | ||||||
#pyo3_path::impl_::deprecations::inspect_type(#self_arg &#self_checker), | ||||||
#(#args),* | ||||||
) | ||||||
} | ||||||
} | ||||||
quote!(function(#self_arg #(#args),*)) | ||||||
} | ||||||
}; | ||||||
let mut call = quote! {{ | ||||||
|
@@ -665,6 +683,7 @@ impl<'a> FnSpec<'a> { | |||||
#pyo3_path::intern!(py, stringify!(#python_name)), | ||||||
#qualname_prefix, | ||||||
#throw_callback, | ||||||
#allow_threads, | ||||||
async move { #pyo3_path::impl_::wrap::OkWrap::wrap(future.await) }, | ||||||
) | ||||||
}}; | ||||||
|
@@ -676,20 +695,21 @@ impl<'a> FnSpec<'a> { | |||||
}}; | ||||||
} | ||||||
call | ||||||
} else { | ||||||
} else if allow_threads { | ||||||
let self_arg = self_arg(); | ||||||
if self_arg.is_empty() { | ||||||
quote! { function(#(#args),*) } | ||||||
let (self_arg_name, self_arg_decl) = if self_arg.is_empty() { | ||||||
(quote!(), quote!()) | ||||||
} else { | ||||||
let self_checker = holders.push_gil_refs_checker(self_arg.span()); | ||||||
quote! { | ||||||
function( | ||||||
// NB #self_arg includes a comma, so none inserted here | ||||||
#pyo3_path::impl_::deprecations::inspect_type(#self_arg &#self_checker), | ||||||
#(#args),* | ||||||
) | ||||||
} | ||||||
} | ||||||
(quote!(__self,), quote! { let (__self,) = (#self_arg); }) | ||||||
}; | ||||||
quote! {{ | ||||||
#self_arg_decl | ||||||
#(let #arg_names = #args;)* | ||||||
py.allow_threads(|| function(#self_arg_name #(#arg_names),*)) | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There's a question in my head here about after #3646 which of the There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Yes, I think so too. Especially since we have already accumulated a significant amount of high risk changes for 0.22 and we can always optimize things in following releases. |
||||||
}} | ||||||
} else { | ||||||
let self_arg = self_arg(); | ||||||
quote!(function(#self_arg #(#args),*)) | ||||||
}; | ||||||
quotes::map_result_into_ptr(quotes::ok_wrap(call, ctx), ctx) | ||||||
}; | ||||||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -21,17 +21,54 @@ use crate::{ | |
pub(crate) mod cancel; | ||
mod waker; | ||
|
||
use crate::marker::Ungil; | ||
pub use cancel::CancelHandle; | ||
|
||
const COROUTINE_REUSED_ERROR: &str = "cannot reuse already awaited coroutine"; | ||
|
||
trait CoroutineFuture: Send { | ||
fn poll(self: Pin<&mut Self>, py: Python<'_>, waker: &Waker) -> Poll<PyResult<PyObject>>; | ||
} | ||
|
||
impl<F, T, E> CoroutineFuture for F | ||
where | ||
F: Future<Output = Result<T, E>> + Send, | ||
T: IntoPy<PyObject> + Send, | ||
E: Into<PyErr> + Send, | ||
{ | ||
fn poll(self: Pin<&mut Self>, py: Python<'_>, waker: &Waker) -> Poll<PyResult<PyObject>> { | ||
self.poll(&mut Context::from_waker(waker)) | ||
.map_ok(|obj| obj.into_py(py)) | ||
.map_err(Into::into) | ||
} | ||
} | ||
|
||
struct AllowThreads<F> { | ||
future: F, | ||
} | ||
|
||
impl<F, T, E> CoroutineFuture for AllowThreads<F> | ||
where | ||
F: Future<Output = Result<T, E>> + Send + Ungil, | ||
T: IntoPy<PyObject> + Send + Ungil, | ||
E: Into<PyErr> + Send + Ungil, | ||
{ | ||
fn poll(self: Pin<&mut Self>, py: Python<'_>, waker: &Waker) -> Poll<PyResult<PyObject>> { | ||
// SAFETY: future field is pinned when self is | ||
let future = unsafe { self.map_unchecked_mut(|a| &mut a.future) }; | ||
py.allow_threads(|| future.poll(&mut Context::from_waker(waker))) | ||
.map_ok(|obj| obj.into_py(py)) | ||
.map_err(Into::into) | ||
} | ||
} | ||
|
||
/// Python coroutine wrapping a [`Future`]. | ||
#[pyclass(crate = "crate")] | ||
pub struct Coroutine { | ||
name: Option<Py<PyString>>, | ||
qualname_prefix: Option<&'static str>, | ||
throw_callback: Option<ThrowCallback>, | ||
future: Option<Pin<Box<dyn Future<Output = PyResult<PyObject>> + Send>>>, | ||
future: Option<Pin<Box<dyn CoroutineFuture>>>, | ||
waker: Option<Arc<AsyncioWaker>>, | ||
} | ||
|
||
|
@@ -46,23 +83,23 @@ impl Coroutine { | |
name: Option<Py<PyString>>, | ||
qualname_prefix: Option<&'static str>, | ||
throw_callback: Option<ThrowCallback>, | ||
allow_threads: bool, | ||
future: F, | ||
) -> Self | ||
where | ||
F: Future<Output = Result<T, E>> + Send + 'static, | ||
T: IntoPy<PyObject>, | ||
E: Into<PyErr>, | ||
F: Future<Output = Result<T, E>> + Send + Ungil + 'static, | ||
T: IntoPy<PyObject> + Send + Ungil, | ||
E: Into<PyErr> + Send + Ungil, | ||
{ | ||
let wrap = async move { | ||
let obj = future.await.map_err(Into::into)?; | ||
// SAFETY: GIL is acquired when future is polled (see `Coroutine::poll`) | ||
Ok(obj.into_py(unsafe { Python::assume_gil_acquired() })) | ||
}; | ||
Self { | ||
name, | ||
qualname_prefix, | ||
throw_callback, | ||
future: Some(Box::pin(wrap)), | ||
future: Some(if allow_threads { | ||
Box::pin(AllowThreads { future }) | ||
} else { | ||
Box::pin(future) | ||
}), | ||
waker: None, | ||
} | ||
} | ||
|
@@ -88,10 +125,10 @@ impl Coroutine { | |
} else { | ||
self.waker = Some(Arc::new(AsyncioWaker::new())); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe we can split this here and do something like let waker = self
.waker
.get_or_insert_with(|| Arc::new(AsyncioWaker::new())); after the (possible) reset, to avoid the |
||
} | ||
let waker = Waker::from(self.waker.clone().unwrap()); | ||
// poll the Rust future and forward its results if ready | ||
// poll the future and forward its results if ready | ||
// polling is UnwindSafe because the future is dropped in case of panic | ||
let poll = || future_rs.as_mut().poll(&mut Context::from_waker(&waker)); | ||
let waker = Waker::from(self.waker.clone().unwrap()); | ||
let poll = || future_rs.as_mut().poll(py, &waker); | ||
match panic::catch_unwind(panic::AssertUnwindSafe(poll)) { | ||
Ok(Poll::Ready(res)) => { | ||
self.close(); | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍 it looks like this already doesn't work so this makes the error message nicer. One suggestion given the GIL is potentially an outdated idea: