Skip to main content

thread_safe/
thread_safe.rs

1//! Example: share a single `ThreadSafeEngine` across threads.
2//!
3//! `ThreadSafeEngine` is a `Clone` wrapper around
4//! `Arc<Mutex<Box<dyn ScriptEngine>>>`, so each thread gets its own handle to
5//! the same underlying (stateful) engine.
6
7use postscriptum::{EngineType, ThreadSafeEngine, get_engine};
8use std::thread;
9
10fn main() -> postscriptum::Result<()> {
11    let engine = ThreadSafeEngine::new(get_engine(EngineType::Rhai));
12    engine.eval("let x = 0")?;
13
14    let mut handles = Vec::new();
15    for i in 0..4 {
16        let engine = engine.clone();
17        handles.push(thread::spawn(move || {
18            engine.eval(&format!("x = x + {i}; x")).unwrap()
19        }));
20    }
21
22    for handle in handles {
23        println!("thread result: {}", handle.join().unwrap());
24    }
25    Ok(())
26}