-
Hello, I'm writing a GUI (with PyQt5) for some scientific calculations in Python. The calculations are written in Rust. I would like to display the progress of the calculations in the GUI within a progress bar. But I can't figure out how to do so. First my Rust code: #[pyclass]
pub struct Test {
progress: usize
}
#[pymethods]
impl Test {
#[new]
pub fn new() -> Self {
Self {progress: 0}
}
pub fn start(&mut self, py: Python) {
py.allow_threads(move || {
for _ in 0..20 {
std::thread::sleep(std::time::Duration::from_secs_f64(0.1));
self.progress += 1;
}
})
}
pub fn get_progress(&self) -> usize {
self.progress
}
} Now my Python code: import rs_module
import time
from threading import Thread
class T(Thread):
def __init__(self):
Thread.__init__(self)
self._test = None
def run(self):
print("thread started")
self._test = rs_module.Test()
self._test.start()
print("thread finished")
def get_progress(self):
if self._test != None:
print(self._test.get_progress())
else:
print(None)
thread = T()
thread.start()
print("start")
tstart = time.time()
while time.time() - tstart < 10:
time.sleep(1)
thread.get_progress()
print("finish") Running the Python code I get the following error message: print(self._test.get_progress())
RuntimeError: Already mutably borrowed Any suggestions are highly appreciated. |
Beta Was this translation helpful? Give feedback.
Answered by
mejrs
Dec 17, 2022
Replies: 1 comment 10 replies
-
You have the same re-entrancy problem as in https://pyo3.rs/main/class/call.html#what-is-the-cell-for Consider changing it to something like this: #[pyclass]
pub struct Test {
- progress: usize
+ progress: AtomicUsize
}
#[pymethods]
impl Test {
#[new]
pub fn new() -> Self {
- Self {progress: 0}
+ Self {progress: AtomicUsize::new(0)}
}
- pub fn start(&mut self, py: Python) {
+ pub fn start(&self, py: Python) {
py.allow_threads(move || {
for _ in 0..20 {
std::thread::sleep(std::time::Duration::from_secs_f64(0.1));
- self.progress += 1;
+ self.progress.fetch_add(1, Ordering::SeqCst);
}
})
}
pub fn get_progress(&self) -> usize {
- self.progress
+ self.progress.load(Ordering::SeqCst)
}
} |
Beta Was this translation helpful? Give feedback.
10 replies
Answer selected by
KCrux
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You have the same re-entrancy problem as in https://pyo3.rs/main/class/call.html#what-is-the-cell-for
Consider changing it to something like this: