-
Notifications
You must be signed in to change notification settings - Fork 795
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
Lazy type objects without once_cell #758
Merged
Merged
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,12 @@ | ||
// Copyright (c) 2017-present PyO3 Project and Contributors | ||
//! Python type object information | ||
|
||
use crate::err::PyResult; | ||
use crate::instance::Py; | ||
use crate::pyclass::{create_type_object, PyClass}; | ||
use crate::pyclass::{initialize_type_object, PyClass}; | ||
use crate::pyclass_init::PyObjectInit; | ||
use crate::types::{PyAny, PyType}; | ||
use crate::{ffi, AsPyPointer, Python}; | ||
use once_cell::sync::OnceCell; | ||
use std::cell::{Cell, UnsafeCell}; | ||
use std::ptr::NonNull; | ||
|
||
/// `T: PyObjectLayout<U>` represents that `T` is a concrete representaion of `U` in Python heap. | ||
|
@@ -92,19 +91,19 @@ pub unsafe trait PyTypeInfo: Sized { | |
/// Initializer for layout | ||
type Initializer: PyObjectInit<Self>; | ||
|
||
/// PyTypeObject instance for this type, guaranteed to be global and initialized. | ||
fn type_object() -> NonNull<ffi::PyTypeObject>; | ||
/// PyTypeObject instance for this type. | ||
fn type_object() -> &'static ffi::PyTypeObject; | ||
|
||
/// Check if `*mut ffi::PyObject` is instance of this type | ||
fn is_instance(object: &PyAny) -> bool { | ||
unsafe { | ||
ffi::PyObject_TypeCheck(object.as_ptr(), Self::type_object().as_ptr() as *mut _) != 0 | ||
ffi::PyObject_TypeCheck(object.as_ptr(), Self::type_object() as *const _ as _) != 0 | ||
} | ||
} | ||
|
||
/// Check if `*mut ffi::PyObject` is exact instance of this type | ||
fn is_exact_instance(object: &PyAny) -> bool { | ||
unsafe { (*object.as_ptr()).ob_type == Self::type_object().as_ptr() as *mut _ } | ||
unsafe { (*object.as_ptr()).ob_type == Self::type_object() as *const _ as _ } | ||
} | ||
} | ||
|
||
|
@@ -124,49 +123,68 @@ where | |
T: PyTypeInfo, | ||
{ | ||
fn type_object() -> Py<PyType> { | ||
unsafe { Py::from_borrowed_ptr(<Self as PyTypeInfo>::type_object().as_ptr() as *mut _) } | ||
unsafe { Py::from_borrowed_ptr(<Self as PyTypeInfo>::type_object() as *const _ as _) } | ||
} | ||
} | ||
|
||
/// Type used to store static type objects | ||
/// Lazy type object for Exceptions | ||
#[doc(hidden)] | ||
pub struct LazyTypeObject { | ||
cell: OnceCell<NonNull<ffi::PyTypeObject>>, | ||
} | ||
pub struct LazyHeapType(UnsafeCell<Option<NonNull<ffi::PyTypeObject>>>); | ||
|
||
impl LazyTypeObject { | ||
impl LazyHeapType { | ||
pub const fn new() -> Self { | ||
Self { | ||
cell: OnceCell::new(), | ||
} | ||
Self(UnsafeCell::new(None)) | ||
} | ||
|
||
pub fn get_or_init<F>(&self, constructor: F) -> PyResult<NonNull<ffi::PyTypeObject>> | ||
pub fn get_or_init<F>(&self, constructor: F) -> NonNull<ffi::PyTypeObject> | ||
where | ||
F: Fn() -> PyResult<NonNull<ffi::PyTypeObject>>, | ||
F: Fn(Python) -> NonNull<ffi::PyTypeObject>, | ||
{ | ||
Ok(*self.cell.get_or_try_init(constructor)?) | ||
if let Some(value) = unsafe { &*self.0.get() } { | ||
return value.clone(); | ||
} | ||
// We have to get the GIL before setting the value to the global!!! | ||
let gil = Python::acquire_gil(); | ||
unsafe { | ||
*self.0.get() = Some(constructor(gil.python())); | ||
(*self.0.get()).unwrap() | ||
} | ||
} | ||
} | ||
|
||
pub fn get_pyclass_type<T: PyClass>(&self) -> NonNull<ffi::PyTypeObject> { | ||
self.get_or_init(|| { | ||
// automatically initialize the class on-demand | ||
let gil = Python::acquire_gil(); | ||
let py = gil.python(); | ||
let boxed = create_type_object::<T>(py, T::MODULE)?; | ||
Ok(unsafe { NonNull::new_unchecked(Box::into_raw(boxed)) }) | ||
}) | ||
.unwrap_or_else(|e| { | ||
// This is necessary for making static `LazyHeapType`s | ||
// | ||
// Type objects are shared between threads by the Python interpreter anyway, so it is no worse | ||
// to allow sharing on the Rust side too. | ||
unsafe impl Sync for LazyHeapType {} | ||
|
||
/// Lazy type object for PyClass | ||
#[doc(hidden)] | ||
pub struct LazyStaticType { | ||
value: UnsafeCell<ffi::PyTypeObject>, | ||
initialized: Cell<bool>, | ||
} | ||
|
||
impl LazyStaticType { | ||
pub const fn new() -> Self { | ||
LazyStaticType { | ||
value: UnsafeCell::new(ffi::PyTypeObject_INIT), | ||
initialized: Cell::new(false), | ||
} | ||
} | ||
pub fn get<T: PyClass>(&self) -> &ffi::PyTypeObject { | ||
if !self.initialized.get() { | ||
let gil = Python::acquire_gil(); | ||
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. Same comment applies as for |
||
let py = gil.python(); | ||
e.print(py); | ||
panic!("An error occurred while initializing class {}", T::NAME) | ||
}) | ||
initialize_type_object::<T>(py, T::MODULE, unsafe { &mut *self.value.get() }) | ||
.unwrap_or_else(|e| { | ||
e.print(py); | ||
panic!("An error occurred while initializing class {}", T::NAME) | ||
}); | ||
self.initialized.set(true); | ||
} | ||
unsafe { &*self.value.get() } | ||
} | ||
} | ||
|
||
// This is necessary for making static `LazyTypeObject`s | ||
// | ||
// Type objects are shared between threads by the Python interpreter anyway, so it is no worse | ||
// to allow sharing on the Rust side too. | ||
unsafe impl Sync for LazyTypeObject {} | ||
// This is necessary for making static `LazyStaticType`s | ||
unsafe impl Sync for LazyStaticType {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
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's unlikely to happen in practice, but there's nothing to prevent two or more threads reaching this point at the same time, which would then lead to
value
being initialized multiple times. Whether this is a problem, I'm not sure.We could avoid this by checking again that
value
is stillNone
after the GIL lock is acquired, and exiting early if some other thread initializedvalue
while this thread was waiting for the GIL.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.
Thank you.
I changed this to use
AtomicBool