Radish alpha
r
rad:zwTxygwuz5LDGBq255RA2CbNGrz8
Radicle CI broker
Radicle
Git
feat: add abstraction for worker threads
Lars Wirzenius committed 10 months ago
commit beb35a1b11608011573a45b427cb5c0fbcb5d795
parent 6c505bb
2 files changed +37 -0
modified src/lib.rs
@@ -29,3 +29,4 @@ pub mod sensitive;
pub mod test;
pub mod timeoutcmd;
pub mod util;
+
pub mod worker;
added src/worker.rs
@@ -0,0 +1,36 @@
+
//! An abstraction for worker threads.
+
//!
+
//! The abstraction provided some consistency on how worker threads
+
//! are implemented and used, as well as logging. A worker thread does
+
//! what it does. The abstraction is not meant to constrain that.
+

+
use std::thread::{spawn, JoinHandle};
+

+
/// Start a new thread. Caller must catch the thread handle and
+
/// join it to wait for thread to end.
+
pub fn start_thread<W: Worker>(mut o: W) -> JoinHandle<Result<(), W::Error>> {
+
    let name = o.name();
+
    spawn(move || {
+
        eprintln!("start worker {name}");
+
        let result = o.work();
+
        eprintln!("end worker {name}: result={result:?}");
+
        result
+
    })
+
}
+

+
/// A worker thread.
+
pub trait Worker: Send + 'static {
+
    /// Name of thread, or kind of thread. Used for logging only.
+
    const NAME: &str;
+

+
    /// Type of error from this worker.
+
    type Error: std::fmt::Debug + Send;
+

+
    /// Do the work the thread is supposed to do.
+
    fn work(&mut self) -> Result<(), Self::Error>;
+

+
    /// Return name of thread as an owned string.
+
    fn name(&self) -> String {
+
        Self::NAME.to_string()
+
    }
+
}