Function procspawn::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)
4
5
6
7
8
fn main() {
    procspawn::init();
    let mut handle = spawn((), |()| loop {});
    handle.kill().unwrap();
}
More examples
Hide additional examples
examples/args.rs (line 6)
3
4
5
6
7
8
9
10
11
fn main() {
    procspawn::init();

    let handle = spawn((), |()| std::env::args().collect::<Vec<_>>());

    let args = handle.join().unwrap();

    println!("args in subprocess: {:?}", args);
}
examples/simple.rs (lines 6-9)
3
4
5
6
7
8
9
10
11
12
fn main() {
    procspawn::init();

    let handle = spawn((1, 2), |(a, b)| {
        println!("in process: {:?} {:?}", a, b);
        a + b
    });

    println!("result: {}", handle.join().unwrap());
}
examples/timeout.rs (lines 8-10)
5
6
7
8
9
10
11
12
13
fn main() {
    procspawn::init();

    let mut handle = spawn((), |()| {
        thread::sleep(Duration::from_secs(10));
    });

    println!("result: {:?}", handle.join_timeout(Duration::from_secs(1)));
}
examples/join.rs (line 6)
3
4
5
6
7
8
9
10
11
12
13
fn main() {
    procspawn::init();

    let five = spawn(5, fibonacci);
    let ten = spawn(10, fibonacci);
    let thirty = spawn(30, fibonacci);
    assert_eq!(five.join().unwrap(), 5);
    assert_eq!(ten.join().unwrap(), 55);
    assert_eq!(thirty.join().unwrap(), 832_040);
    println!("Successfully calculated fibonacci values!");
}
examples/panic.rs (lines 6-8)
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fn main() {
    procspawn::init();

    let handle = spawn((), |()| {
        panic!("Whatever!");
    });

    match handle.join() {
        Ok(()) => unreachable!(),
        Err(err) => {
            let panic = err.panic_info().expect("got a non panic error");
            println!("process panicked with {}", panic.message());
            println!("{:#?}", panic);
        }
    }
}