Alexis Purslane
Alexis Purslane

Reputation: 1390

Receiver closing and returning a SendError on attempt to send over channel

I'm trying to set up a two-way communication between two threads: the child thread can both send to and receive from the parent, and the parent can both send to and receive from the child. Due to the fact that channels in Rust are unidirectional, I'm using a set of two channels, organized like this (a snippet from my homebrewed threading library):

let (tx, rx) = channel();
let (tx2, rx2) = channel();

(Endpoint {
     sender: tx2,
     receiver: rx,
 },
 Endpoint {
     sender: tx,
     receiver: rx2,
 })

My code in my setup function looks like this:

let BiChannel {
    e1: world,
    e2: thread,
} = BiChannel::new();

let ws = WorldState {
    ...
    thread_endpoint: thread,
};
std::thread::spawn(threading::handle_life(world));

In this snippet, the threading::handle_life function returns a move closure that uses the Endpoint passed (world in the code above) to communicate to the parent thread, while the parent thread uses ws.thread_endpoint to talk to the child thread.

I'm calling unwrap on all calls to send on the endpoints, so if if it fails to send, it crashes. Sure enough, I'm getting a runtime error that looks like this:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: "SendError(..)"', src/libcore/result.rs:860
note: Run with `RUST_BACKTRACE=1` for a backtrace.

The documentation on this is pretty scanty, but what little I could figure out was that this only happens if the channel is closed.

Upvotes: 2

Views: 1600

Answers (1)

Alexis Purslane
Alexis Purslane

Reputation: 1390

As it turns out, the problem was that I had forgotten to put the message-receiving code in the child thread in an infinite loop, so as soon as it received its first message, it quit and the corresponding channel closed.

Upvotes: 3

Related Questions