-
Notifications
You must be signed in to change notification settings - Fork 917
docs: extend documentation on Sync and thread-safety
#4695
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
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
f1d127a
guide: extend documentation on `Sync` and thread-safety
davidhewitt bfdd00e
Update guide/src/class/thread-safety.md
davidhewitt 8352396
Apply suggestions from code review
davidhewitt 610e23e
threadsafe -> thread-safe
davidhewitt 36daecf
datastructure -> data structure
davidhewitt eaf3b52
fill out missing sections
davidhewitt eaff7f4
remove dead paragraph
davidhewitt 5a66244
Merge branch 'main' into sync-docs
davidhewitt ec40f51
fix guide build
davidhewitt 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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 |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| # `#[pyclass]` thread safety | ||
|
|
||
| Python objects are freely shared between threads by the Python interpreter. This means that: | ||
| - there is no control which thread might eventually drop the `#[pyclass]` object, meaning `Send` is required. | ||
| - multiple threads can potentially be reading the `#[pyclass]` data simultaneously, meaning `Sync` is required. | ||
|
|
||
| This section of the guide discusses various data structures which can be used to make types satisfy these requirements. | ||
|
|
||
| In special cases where it is known that your Python application is never going to use threads (this is rare!), these thread-safety requirements can be opted-out with [`#[pyclass(unsendable)]`](../class.md#customizing-the-class), at the cost of making concurrent access to the Rust data be runtime errors. This is only for very specific use cases; it is almost always better to make proper thread-safe types. | ||
|
|
||
| ## Making `#[pyclass]` types thread-safe | ||
|
|
||
| The general challenge with thread-safety is to make sure that two threads cannot produce a data race, i.e. unsynchronized writes to the same data at the same time. A data race produces an unpredictable result and is forbidden by Rust. | ||
|
|
||
| By default, `#[pyclass]` employs an ["interior mutability" pattern](../class.md#bound-and-interior-mutability) to allow for either multiple `&T` references or a single exclusive `&mut T` reference to access the data. This allows for simple `#[pyclass]` types to be thread-safe automatically, at the cost of runtime checking for concurrent access. Errors will be raised if the usage overlaps. | ||
|
|
||
| For example, the below simple class is thread-safe: | ||
|
|
||
| ```rust | ||
| # use pyo3::prelude::*; | ||
|
|
||
| #[pyclass] | ||
| struct MyClass { | ||
| x: i32, | ||
| y: i32, | ||
| } | ||
|
|
||
| #[pymethods] | ||
| impl MyClass { | ||
| fn get_x(&self) -> i32 { | ||
| self.x | ||
| } | ||
|
|
||
| fn set_y(&mut self, value: i32) { | ||
| self.y = value; | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| In the above example, if calls to `get_x` and `set_y` overlap (from two different threads) then at least one of those threads will experience a runtime error indicating that the data was "already borrowed". | ||
|
|
||
| To avoid these errors, you can take control of the interior mutability yourself in one of the following ways. | ||
|
|
||
| ### Using atomic data structures | ||
|
|
||
| To remove the possibility of having overlapping `&self` and `&mut self` references produce runtime errors, consider using `#[pyclass(frozen)]` and use [atomic data structures](https://doc.rust-lang.org/std/sync/atomic/) to control modifications directly. | ||
|
|
||
| For example, a thread-safe version of the above `MyClass` using atomic integers would be as follows: | ||
|
|
||
| ```rust | ||
| # use pyo3::prelude::*; | ||
| use std::sync::atomic::{AtomicI32, Ordering}; | ||
|
|
||
| #[pyclass(frozen)] | ||
| struct MyClass { | ||
| x: AtomicI32, | ||
| y: AtomicI32, | ||
| } | ||
|
|
||
| #[pymethods] | ||
| impl MyClass { | ||
| fn get_x(&self) -> i32 { | ||
| self.x.load(Ordering::Relaxed) | ||
| } | ||
|
|
||
| fn set_y(&self, value: i32) { | ||
| self.y.store(value, Ordering::Relaxed) | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| ### Using locks | ||
|
|
||
| An alternative to atomic data structures is to use [locks](https://doc.rust-lang.org/std/sync/struct.Mutex.html) to make threads wait for access to shared data. | ||
|
|
||
| For example, a thread-safe version of the above `MyClass` using locks would be as follows: | ||
|
|
||
| ```rust | ||
| # use pyo3::prelude::*; | ||
| use std::sync::Mutex; | ||
|
|
||
| struct MyClassInner { | ||
| x: i32, | ||
| y: i32, | ||
| } | ||
|
|
||
| #[pyclass(frozen)] | ||
| struct MyClass { | ||
| inner: Mutex<MyClassInner> | ||
| } | ||
|
|
||
| #[pymethods] | ||
| impl MyClass { | ||
| fn get_x(&self) -> i32 { | ||
| self.inner.lock().expect("lock not poisoned").x | ||
| } | ||
|
|
||
| fn set_y(&self, value: i32) { | ||
| self.inner.lock().expect("lock not poisoned").y = value; | ||
| } | ||
| } | ||
| ``` | ||
|
|
||
| ### Wrapping unsynchronized data | ||
|
|
||
| In some cases, the data structures stored within a `#[pyclass]` may themselves not be thread-safe. Rust will therefore not implement `Send` and `Sync` on the `#[pyclass]` type. | ||
|
|
||
| To achieve thread-safety, a manual `Send` and `Sync` implementation is required which is `unsafe` and should only be done following careful review of the soundness of the implementation. Doing this for PyO3 types is no different than for any other Rust code, [the Rustonomicon](https://doc.rust-lang.org/nomicon/send-and-sync.html) has a great discussion on this. |
This file contains hidden or 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
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.