Function spawn

Source
pub fn spawn<A: Serialize + DeserializeOwned, R: Serialize + DeserializeOwned>(
    args: A,
    f: fn(A) -> R,
) -> JoinHandle<R>
Expand description

Spawn a new process to run a function with some payload.

// call this early in your main() function.  This is where all spawned
// functions will be invoked.
procspawn::init();

let data = vec![1, 2, 3, 4];
let handle = procspawn::spawn(data, |data| {
    println!("Received data {:?}", &data);
    data.into_iter().sum::<i64>()
});
let result = handle.join().unwrap();
Examples found in repository?
examples/kill.rs (line 6)
4fn main() {
5    procspawn::init();
6    let mut handle = spawn((), |()| loop {});
7    handle.kill().unwrap();
8}
More examples
Hide additional examples
examples/args.rs (line 6)
3fn main() {
4    procspawn::init();
5
6    let handle = spawn((), |()| std::env::args().collect::<Vec<_>>());
7
8    let args = handle.join().unwrap();
9
10    println!("args in subprocess: {:?}", args);
11}
examples/simple.rs (lines 6-9)
3fn main() {
4    procspawn::init();
5
6    let handle = spawn((1, 2), |(a, b)| {
7        println!("in process: {:?} {:?}", a, b);
8        a + b
9    });
10
11    println!("result: {}", handle.join().unwrap());
12}
examples/timeout.rs (lines 8-10)
5fn main() {
6    procspawn::init();
7
8    let mut handle = spawn((), |()| {
9        thread::sleep(Duration::from_secs(10));
10    });
11
12    println!("result: {:?}", handle.join_timeout(Duration::from_secs(1)));
13}
examples/join.rs (line 6)
3fn main() {
4    procspawn::init();
5
6    let five = spawn(5, fibonacci);
7    let ten = spawn(10, fibonacci);
8    let thirty = spawn(30, fibonacci);
9    assert_eq!(five.join().unwrap(), 5);
10    assert_eq!(ten.join().unwrap(), 55);
11    assert_eq!(thirty.join().unwrap(), 832_040);
12    println!("Successfully calculated fibonacci values!");
13}
examples/panic.rs (lines 6-8)
3fn main() {
4    procspawn::init();
5
6    let handle = spawn((), |()| {
7        panic!("Whatever!");
8    });
9
10    match handle.join() {
11        Ok(()) => unreachable!(),
12        Err(err) => {
13            let panic = err.panic_info().expect("got a non panic error");
14            println!("process panicked with {}", panic.message());
15            println!("{:#?}", panic);
16        }
17    }
18}