Rust中的任务失败

时间:2014-09-03 15:27:42

标签: task rust

我正在寻找有关任务失败的一些说明。据我了解,如果任务1产生任务2,任务2是任务1的子项。如果任务1失败,它是否会在任务2之后自动失败并清理?

例如,我在套接字上启动i / o任务,如下所示:

spawn(proc() {
    start_new_socket(socket, socket_receiver)
});

我们将调用该任务1.在任务1中,我生成另一个任务:

fn start_new_socket(socket: Socket, receiver: Receiver<Message>) {

    // Write task
    let mut stream_write = socket.stream.clone();
    spawn(proc() {
        loop {
            let msg = receiver.recv();
            msg.send(&mut stream_write).unwrap();
        }
    });

    // Open up a blocking read on this socket
    let mut stream_read = socket.stream.clone();
    loop {        
        let msg = Message::load(&mut stream_read).unwrap();
        match msg.payload {
            Text(ptr) => {
                let json_slice = (*ptr).as_slice();
                println!("Socket: {} recevied: {}", socket.id, json_slice);
                parse_json(json_slice, socket.clone());
            }
            Binary(ptr) => {
                // TODO - Do awesome binary shit
            }
        }
    }    
}

如果任务1 start_new_socket由于EOF或流中的其他内容而失败,那么它启动的写入任务是否也会失败?

1 个答案:

答案 0 :(得分:1)

我使用此代码进行了实验:

use std::io::Timer;
use std::time::Duration;

fn main () {

    spawn(proc() {
        let mut timer = Timer::new().unwrap();
        loop {
            println!("I from subtask !");
            timer.sleep(Duration::seconds(1));
        }
    });

    let mut other_timer = Timer::new().unwrap();
    other_timer.sleep(Duration::seconds(5));
    println!("Gonna fail....");
    other_timer.sleep(Duration::seconds(1));
    fail!("Failed !");
}

输出是:

I from subtask !
I from subtask !
I from subtask !
I from subtask !
I from subtask !
Gonna fail....
I from subtask !
task '<main>' failed at 'Failed !', failing.rs:18
I from subtask !
I from subtask !
I from subtask !
I from subtask !
I from subtask !
I from subtask !
^C

显然不是,当主要任务没有时,子任务不会失败。