Do you need to disable gil / allow threads in rust-spawned threads? #2112
-
Consider this example: #[pyclass]
pub struct Node {
#[pyo3(get, set)]
my_data: String,
stopper: Arc<Mutex<bool>>,
thread_handle: JoinHandle
}
#[pymethods]
impl Node {
#[new]
pub fn new(my_data: String) -> Self {
Node {my_data}
}
pub fn start(&mut self) {
// do I need to disable gil / allow threads here
self.thread_handle = thread::spawn(move || {
// or here?
/// while not stopper { listen to some socket address, work }
});
// might spawn more threads, in a threadpool
}
pub fn stop(&mut self) {
// self.stopper = True
self.thread_handle.join()
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Consequently, you also should not be able to use any Python stuff in the thread without calling |
Beta Was this translation helpful? Give feedback.
-
It depends on what you do in the thread. If you don't release the GIL and something in the spawned thread tries to acquire the GIL, you will deadlock. i.e., the following program will never return: fn main() {
Python::with_gil(|py| {
let handle = std::thread::spawn(|| {
Python::with_gil(|_| {});
});
handle.join().unwrap();
});
} The same is true for other locks, like std's |
Beta Was this translation helpful? Give feedback.
thread::spawn
knows nothing about the GIL, so the spawned code does not hold or acquire the GIL.Consequently, you also should not be able to use any Python stuff in the thread without calling
with_gil
. If you can, that's a bug.