A channel has two halves: a transmitter and a receiver. The transmitter half is the upstream location where you put rubber ducks into the river, and the receiver half is where the rubber duck ends up downstream. One part of your code calls methods on the transmitter with the data you want to send, and another part checks the receiving end for arriving messages. A channel is said to be closed if either the transmitter or receiver half is dropped.
A simple channel creation, code won't do anything, cannot compile yet:
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel();
}
We create a new channel using the mpsc::channel
function; mpsc
stands for multiple producer, single consumer.
The mpsc::channel
function returns a tuple, the first element of which is the sending end--the transmitter--and the second element is the receiving end--the receiver. The abbreviations tx
and rx
are traditionally used in many fields for transmitter and receiver respectively, so we name our variables as such to indicate each end.
Put tx
into a child thread to talk to main thread:
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap();
});
}
Now we add rx
to receive the data in main thread:
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap();
});
let received = rx.recv().unwrap();
println!("Got: {}", received);
}
The receiver has two useful methods: recv
and try_recv
. We’re using recv
, short for receive, which will block the main thread’s execution and wait until a value is sent down the channel. Once a value is sent, recv
will return it in a Result<T, E>
. When the transmitter closes, recv
will return an error to signal that no more values will be coming.
The try_recv
method doesn’t block, but will instead return a Result<T, E>
immediately: an Ok
value holding a message if one is available and an Err
value if there aren’t any messages this time. Using try_recv
is useful if this thread has other work to do while waiting for messages: we could write a loop that calls try_recv
every so often, handles a message if one is available, and otherwise does other work for a little while until checking again.
When we run the code, we will be able to receive the message:
Got: hi
标签:transmitter,mpsc,Thread,thread,channel,using,tx,recv,Rust From: https://www.cnblogs.com/Answer1215/p/18069480