|
| 1 | +## Unbounded Channels |
| 2 | + |
| 3 | +[![tokio-badge]][tokio] [![std-badge]][std] |
| 4 | + |
| 5 | +An [`unbounded channel`] has no limit on how many messages it can hold. The sender never has to wait, |
| 6 | +it can always drop a message in, no matter how many are already sitting there. |
| 7 | + |
| 8 | +Think of it like a digital inbox. It just keeps growing as new messages arrive. There's no cap, |
| 9 | +but if messages pile up faster than they're being read, your program will use more and more memory. |
| 10 | +Sending on an unbounded channel will always succeed as long as the receiving end is still open. |
| 11 | +If the receiver is slow, messages simply queue up and wait. |
| 12 | + |
| 13 | +In this example, two people send messages through a channel. An inbox collects whatever comes |
| 14 | +through. |
| 15 | + |
| 16 | +```rust,edition2018 |
| 17 | +use std::io; |
| 18 | +use tokio::sync::mpsc::unbounded_channel; |
| 19 | +
|
| 20 | +struct Message { |
| 21 | + from: &'static str, |
| 22 | + text: &'static str, |
| 23 | +} |
| 24 | +
|
| 25 | +impl Message { |
| 26 | + fn new(from: &'static str, text: &'static str) -> Self { |
| 27 | + Self { from, text } |
| 28 | + } |
| 29 | +} |
| 30 | +
|
| 31 | +#[tokio::main] |
| 32 | +async fn main() -> io::Result<()> { |
| 33 | + let (message_sender, mut message_receiver) = unbounded_channel(); |
| 34 | +
|
| 35 | + let alice_message_sender = message_sender.clone(); |
| 36 | + let person_one = tokio::task::spawn(async move { |
| 37 | + if let Err(err) = alice_message_sender.send(Message::new("Alice", "Meeting postponed")) { |
| 38 | + eprintln!("Failed to send message from Alice: {}", err); |
| 39 | + } |
| 40 | + }); |
| 41 | +
|
| 42 | + let person_two = tokio::task::spawn(async move { |
| 43 | + if let Err(err) = message_sender.send(Message::new("Bob", "Secret Leaked")) { |
| 44 | + eprintln!("Failed to send message from Bob: {}", err); |
| 45 | + } |
| 46 | + }); |
| 47 | +
|
| 48 | + let mut inbox: Vec<Message> = Vec::new(); |
| 49 | + while let Some(new_book) = message_receiver.recv().await { |
| 50 | + inbox.push(new_book); |
| 51 | + } |
| 52 | +
|
| 53 | + person_one.await?; |
| 54 | + person_two.await?; |
| 55 | +
|
| 56 | + for msg in &inbox { |
| 57 | + println!("{} says: {}", msg.from, msg.text); |
| 58 | + } |
| 59 | +
|
| 60 | + Ok(()) |
| 61 | +} |
| 62 | +``` |
| 63 | + |
| 64 | +> Add `tokio` to `Cargo.toml` with the [`macros`] and [`sync`] features enabled. |
| 65 | +> ```toml |
| 66 | +> [dependencies] |
| 67 | +> tokio = { version = "*", features = ["macros", "sync"] } |
| 68 | +> ``` |
| 69 | +
|
| 70 | +[`macros`]: https://docs.rs/crate/tokio/*/features#macros |
| 71 | +[`sync`]: https://docs.rs/crate/tokio/*/features#sync |
| 72 | +[`unbounded channel`]: https://docs.rs/tokio/*/tokio/sync/mpsc/fn.unbounded_channel.html |
0 commit comments