rhai/examples/threading.rs

70 lines
1.9 KiB
Rust
Raw Normal View History

2022-02-12 05:41:04 +01:00
//! An advanced example showing how to communicate with an `Engine` running in a separate thread via
//! an MPSC channel.
use rhai::Engine;
2021-01-25 04:31:54 +01:00
2021-02-20 16:46:25 +01:00
#[cfg(feature = "sync")]
use std::sync::Mutex;
2021-01-25 04:31:54 +01:00
fn main() {
// Channel: Script -> Master
let (tx_script, rx_master) = std::sync::mpsc::channel();
// Channel: Master -> Script
let (tx_master, rx_script) = std::sync::mpsc::channel();
2021-01-25 05:55:10 +01:00
#[cfg(feature = "sync")]
2021-02-20 16:46:25 +01:00
let (tx_script, rx_script) = (Mutex::new(tx_script), Mutex::new(rx_script));
2021-01-25 05:55:10 +01:00
2021-01-25 04:31:54 +01:00
// Spawn thread with Engine
std::thread::spawn(move || {
// Create Engine
let mut engine = Engine::new();
// Register API
// Notice that the API functions are blocking
2021-01-25 05:55:10 +01:00
#[cfg(not(feature = "sync"))]
2021-01-25 04:31:54 +01:00
engine
2021-02-20 16:46:25 +01:00
.register_fn("get", move || rx_script.recv().unwrap_or_default())
.register_fn("put", move |v: i64| tx_script.send(v).unwrap());
2021-01-25 04:31:54 +01:00
2021-01-25 05:55:10 +01:00
#[cfg(feature = "sync")]
engine
.register_fn("get", move || rx_script.lock().unwrap().recv().unwrap())
.register_fn("put", move |v: i64| {
2021-01-25 05:55:10 +01:00
tx_script.lock().unwrap().send(v).unwrap()
});
2021-01-25 04:31:54 +01:00
// Run script
engine
.run(
2021-01-25 04:31:54 +01:00
r#"
print("Starting script loop...");
loop {
let x = get();
2021-04-04 17:22:45 +02:00
print(`Script Read: ${x}`);
2021-01-25 04:31:54 +01:00
x += 1;
2021-04-04 17:22:45 +02:00
print(`Script Write: ${x}`);
2021-01-25 04:31:54 +01:00
put(x);
}
"#,
)
.unwrap();
});
// This is the main processing thread
println!("Starting main loop...");
let mut value: i64 = 0;
2021-01-25 04:31:54 +01:00
while value < 10 {
println!("Value: {value}");
2021-01-25 04:31:54 +01:00
// Send value to script
tx_master.send(value).unwrap();
// Receive value from script
value = rx_master.recv().unwrap();
}
}