Skip to content

Commit 7762e21

Browse files
committed
fix: keep python thread handle alive
1 parent 3d681f0 commit 7762e21

File tree

1 file changed

+33
-4
lines changed

1 file changed

+33
-4
lines changed

src/progress.rs

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
1-
use std::{collections::BTreeMap, sync::Arc, time::Duration};
1+
use std::{
2+
collections::BTreeMap,
3+
sync::{
4+
mpsc::{sync_channel, SyncSender},
5+
Arc,
6+
},
7+
thread::spawn,
8+
time::Duration,
9+
};
210

311
use anyhow::{Context, Result};
412
use indicatif::ProgressBar;
@@ -10,20 +18,38 @@ use upon::{Engine, Value};
1018
pub struct ProgressHandler {
1119
engine: Engine<'static>,
1220
template: String,
13-
callback: Arc<Py<PyAny>>,
1421
rate: Duration,
1522
n_cores: usize,
23+
updates: SyncSender<String>,
1624
}
1725

1826
impl ProgressHandler {
1927
pub fn new(callback: Arc<Py<PyAny>>, rate: Duration, template: String, n_cores: usize) -> Self {
2028
let engine = Engine::new();
29+
30+
let (update_tx, update_rx) = sync_channel(1);
31+
32+
spawn(move || {
33+
Python::with_gil(move |py| {
34+
py.allow_threads(move || {
35+
let update = update_rx.recv();
36+
let Ok(update) = update else {
37+
return;
38+
};
39+
let res = Python::with_gil(|py| callback.call1(py, (update,)));
40+
if let Err(err) = res {
41+
eprintln!("Error in progress callback: {err}");
42+
}
43+
});
44+
});
45+
});
46+
2147
Self {
2248
engine,
23-
callback,
2449
rate,
2550
template,
2651
n_cores,
52+
updates: update_tx,
2753
}
2854
}
2955

@@ -50,7 +76,10 @@ impl ProgressHandler {
5076
progress_to_value(progress_update_count, self.n_cores, time_sampling, progress);
5177
let rendered = template.render_from(&self.engine, &progress).to_string();
5278
let rendered = rendered.unwrap_or_else(|err| format!("{err}"));
53-
let _ = Python::with_gil(|py| self.callback.call1(py, (rendered,)));
79+
if let Err(e) = self.updates.send(rendered) {
80+
eprintln!("Could not send progress update: {e}");
81+
return;
82+
}
5483
progress_update_count += 1;
5584
};
5685

0 commit comments

Comments
 (0)