Using PyO3, from a long-running Rust application I want to be able to call some functions many times. Before that I need to import a few modules. How can I do the imports just once and then re-use the PyModule
s from other threads that call the functions? Here is a simplified example of what I'm trying to do:
let x: PyResult<&PyModule> = Python::with_gil(|py| {
let pm = py.import("time")?; // Only do this once
Ok(pm)
});
let my_module = x.unwrap();
let mut handles = vec![];
for i in 0..2 {
let t = thread::spawn(|| {
Python::with_gil(|py| {
// Use my_module here
});
});
handles.push(t);
}
for h in handles {
h.join();
}
The above code will not compile due to lifetime errors. How should I change it, so that I can use that shared my_module
instance across my app, in different threads?