Skip to content

Commit 469bc43

Browse files
committed
readme
1 parent 5a206a1 commit 469bc43

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

README.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,46 @@ Make sure to use `call_async_function` for async python functions. Using `call_f
8888
probably raise an error.
8989
`call_async_function` is not available for RustPython.
9090

91+
### Thread Safety
92+
93+
The `PyRunner` is designed to be safely shared across multiple threads.
94+
95+
You can clone a `PyRunner` instance and move it into different threads. All commands sent from any clone are funneled through a channel to a single, dedicated OS thread that houses the Python interpreter. This design correctly handles Python's Global Interpreter Lock (GIL) by ensuring that only one Python operation is attempted at any given time within that interpreter instance.
96+
97+
Here is an example of using `PyRunner` from multiple `std::thread`s:
98+
99+
```rust
100+
use async_py::{PyRunner, PyRunnerError};
101+
use std::thread;
102+
103+
fn main() -> Result<(), PyRunnerError> {
104+
let runner = PyRunner::new();
105+
runner.run_sync("x = 0")?;
106+
107+
let mut handles = vec![];
108+
109+
for i in 0..5 {
110+
let runner_clone = runner.clone();
111+
let handle = thread::spawn(move || {
112+
// Use the _sync versions for non-async contexts
113+
runner_clone.run_sync(&format!("x += {}", i)).unwrap();
114+
});
115+
handles.push(handle);
116+
}
117+
118+
for handle in handles {
119+
handle.join().unwrap();
120+
}
121+
122+
let final_x = runner.read_variable_sync("x")?;
123+
// Expected: 0 + 1 + 2 + 3 + 4 = 10
124+
assert_eq!(final_x, Value::Number(10.into()));
125+
126+
runner.stop_sync()?;
127+
Ok(())
128+
}
129+
```
130+
91131
### Using a venv
92132
It is generally recommended to use a venv to install pip packages.
93133
While you cannot switch the interpreter version with this crate, you can use an

0 commit comments

Comments
 (0)