1
0
dust/dust-lang/examples/interpreter_async.rs

53 lines
1.2 KiB
Rust
Raw Normal View History

2024-07-15 20:42:49 +00:00
use std::{
sync::{mpsc::channel, Arc},
thread,
time::Duration,
};
use dust_lang::*;
fn run_fibnacci(interpreter: &Interpreter, i: u8) -> Value {
// These double brackets are not Dust syntax, it's just an escape sequence for Rust's format!
// macro.
let source = Arc::from(format!(
"
fib = fn (i: int) -> int {{
if i <= 1 {{
i
}} else {{
fib(i - 1) + fib(i - 2)
}}
}}
fib({i})"
));
interpreter
.run(Arc::from(i.to_string()), source)
.unwrap() // Panic if there are errors.
.unwrap() // Panic if the no value is returned.
}
fn main() {
2024-07-15 20:58:54 +00:00
let interpreter = Interpreter::new();
2024-07-15 20:42:49 +00:00
let (tx, rx) = channel();
for i in 1..10 {
let interpreter = interpreter.clone();
let tx = tx.clone();
2024-07-15 20:58:54 +00:00
println!("Spawning thread for fib({})", i);
2024-07-15 20:42:49 +00:00
thread::spawn(move || {
let value = run_fibnacci(&interpreter, i);
tx.send(value).unwrap();
});
}
// Give the threads half a second to finish.
while let Ok(value) = rx.recv_timeout(Duration::from_millis(500)) {
println!("{}", value);
}
}