1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
//! Multi-producer multi-consumer channels for message passing. //! //! Crossbeam's channels are an alternative to the [`std::sync::mpsc`] channels provided by the //! standard library. They are an improvement in terms of performance, ergonomics, and features. //! //! Here's a quick example: //! //! ``` //! use crossbeam_channel as channel; //! //! // Create a channel of unbounded capacity. //! let (s, r) = channel::unbounded(); //! //! // Send a message into the channel. //! s.send("Hello world!"); //! //! // Receive the message from the channel. //! assert_eq!(r.recv(), Some("Hello world!")); //! ``` //! //! # Types of channels //! //! Channels are created using two functions: //! //! * [`bounded`] creates a channel of bounded capacity, i.e. there is a limit to how many messages //! it can hold. //! //! * [`unbounded`] creates a channel of unbounded capacity, i.e. it can contain arbitrary number //! of messages at any time. //! //! Both functions return two handles: a sender and a receiver. Senders and receivers represent //! two opposite sides of a channel. Messages are sent into the channel using senders and received //! using receivers. //! //! Creating a bounded channel: //! //! ``` //! use crossbeam_channel as channel; //! //! // Create a channel that can hold at most 5 messages at a time. //! let (s, r) = channel::bounded(5); //! //! // Can only send 5 messages without blocking. //! for i in 0..5 { //! s.send(i); //! } //! //! // Another call to `send` would block because the channel is full. //! // s.send(5); //! ``` //! //! Creating an unbounded channel: //! //! ``` //! use crossbeam_channel as channel; //! //! // Create an unbounded channel. //! let (s, r) = channel::unbounded(); //! //! // Can send any number of messages into the channel without blocking. //! for i in 0..1000 { //! s.send(i); //! } //! ``` //! //! A rather special case is a bounded, zero-capacity channel. This kind of channel cannot hold any //! messages at all! In order to send a message through the channel, a sending thread and a //! receiving thread have to pair up at the same time: //! //! ``` //! use std::thread; //! use crossbeam_channel as channel; //! //! // Create a zero-capacity channel. //! let (s, r) = channel::bounded(0); //! //! // Spawn a thread that sends a message into the channel. //! // Sending blocks until a receive operation appears on the other side. //! thread::spawn(move || s.send("Hi!")); //! //! // Receive the message. //! // Receiving blocks until a send operation appears on the other side. //! assert_eq!(r.recv(), Some("Hi!")); //! ``` //! //! # Sharing channels //! //! Senders and receivers can be either shared by reference or cloned and then sent to other //! threads. There can be multiple senders and multiple receivers associated with the same channel. //! //! Sharing by reference: //! //! ``` //! # extern crate crossbeam_channel; //! extern crate crossbeam; //! # fn main() { //! use crossbeam_channel as channel; //! //! let (s, r) = channel::unbounded(); //! //! crossbeam::scope(|scope| { //! // Spawn a thread that sends one message and then receives one. //! scope.spawn(|| { //! s.send(1); //! r.recv().unwrap(); //! }); //! //! // Spawn another thread that does the same thing. //! scope.spawn(|| { //! s.send(2); //! r.recv().unwrap(); //! }); //! }); //! //! # } //! ``` //! //! Sharing by cloning: //! //! ``` //! use std::thread; //! use crossbeam_channel as channel; //! //! let (s1, r1) = channel::unbounded(); //! let (s2, r2) = (s1.clone(), r1.clone()); //! //! // Spawn a thread that sends one message and then receives one. //! thread::spawn(move || { //! s1.send(1); //! r1.recv().unwrap(); //! }); //! //! // Spawn another thread that receives a message and then sends one. //! thread::spawn(move || { //! r2.recv().unwrap(); //! s2.send(2); //! }); //! ``` //! //! Note that cloning only creates a new reference to the same sending or receiving side. Cloning //! does not create a new channel. //! //! # Closing channels //! //! When all senders associated with a channel get dropped, the channel becomes closed. No more //! messages can be sent, but any remaining messages can still be received. Receive operations on a //! closed channel never block, even if the channel is empty. //! //! ``` //! use crossbeam_channel as channel; //! //! let (s, r) = channel::unbounded(); //! s.send(1); //! s.send(2); //! s.send(3); //! //! // The only sender is dropped, closing the channel. //! drop(s); //! //! // The remaining messages can be received. //! assert_eq!(r.recv(), Some(1)); //! assert_eq!(r.recv(), Some(2)); //! assert_eq!(r.recv(), Some(3)); //! //! // There are no more messages in the channel. //! assert!(r.is_empty()); //! //! // Note that calling `r.recv()` will not block. //! // Instead, `None` is returned immediately. //! assert_eq!(r.recv(), None); //! ``` //! //! # Blocking and non-blocking operations //! //! Sending a message into a full bounded channel will block until an empty slot in the channel //! becomes available. Sending into an unbounded channel never blocks because there is always //! enough space in it. Zero-capacity channels are always empty, and sending blocks until a receive //! operation appears on the other side of the channel. //! //! Receiving from an empty channel blocks until a message is sent into the channel or the channel //! becomes closed. Zero-capacity channels are always empty, and receiving blocks until a send //! operation appears on the other side of the channel or it becomes closed. //! //! There is also a non-blocking method [`try_recv`], which receives a message if it is immediately //! available, or returns `None` otherwise. //! //! ``` //! use crossbeam_channel as channel; //! //! let (s, r) = channel::bounded(1); //! //! // Send a message into the channel. //! s.send("foo"); //! //! // This call would block because the channel is full. //! // s.send("bar"); //! //! // Receive the message. //! assert_eq!(r.recv(), Some("foo")); //! //! // This call would block because the channel is empty. //! // r.recv(); //! //! // Try receiving a message without blocking. //! assert_eq!(r.try_recv(), None); //! //! // Close the channel. //! drop(s); //! //! // This call doesn't block because the channel is now closed. //! assert_eq!(r.recv(), None); //! ``` //! //! For greater control over blocking, consider using the [`select!`] macro. //! //! # Iteration //! //! A channel is a special kind of iterator, where items can be dynamically produced by senders and //! consumed by receivers. Indeed, [`Receiver`] implements the [`Iterator`] trait, and calling //! [`next`] is equivalent to calling [`recv`]. //! //! ``` //! use std::thread; //! use crossbeam_channel as channel; //! //! let (s, r) = channel::unbounded(); //! //! thread::spawn(move || { //! s.send(1); //! s.send(2); //! s.send(3); //! // `s` was moved into the closure so now it gets dropped, //! // thus closing the channel. //! }); //! //! // Collect all messages from the channel. //! // //! // Note that the call to `collect` blocks until the channel becomes //! // closed and empty, i.e. until `r.next()` returns `None`. //! let v: Vec<_> = r.collect(); //! assert_eq!(v, [1, 2, 3]); //! ``` //! //! # Select //! //! The [`select!`] macro allows declaring a set of channel operations and blocking until any one //! of them becomes ready. Finally, one of the operations is executed. If multiple operations //! are ready at the same time, a random one is chosen. It is also possible to declare a `default` //! case that gets executed if none of the operations are initially ready. //! //! An example of receiving a message from two channels, whichever becomes ready first: //! //! ``` //! # #[macro_use] //! # extern crate crossbeam_channel; //! # fn main() { //! use std::thread; //! use crossbeam_channel as channel; //! //! let (s1, r1) = channel::unbounded(); //! let (s2, r2) = channel::unbounded(); //! //! thread::spawn(move || s1.send("foo")); //! thread::spawn(move || s2.send("bar")); //! //! // Only one of these two receive operations will be executed. //! select! { //! recv(r1, msg) => assert_eq!(msg, Some("foo")), //! recv(r2, msg) => assert_eq!(msg, Some("bar")), //! } //! # } //! ``` //! //! For more details, take a look at the documentation for [`select!`]. //! //! If you need to dynamically add cases rather than define them statically inside the macro, use //! [`Select`] instead. //! //! # Frequently asked questions //! //! ### How to try receiving a message, but also check whether the channel is empty or closed? //! //! Use the [`select!`] macro: //! //! ```rust //! # #[macro_use] //! # extern crate crossbeam_channel; //! # fn main() { //! use crossbeam_channel as channel; //! //! let (s, r) = channel::unbounded(); //! s.send("hello"); //! //! select! { //! recv(r, msg) => match msg { //! Some(msg) => println!("received {:?}", msg), //! None => println!("the channel is closed"), //! } //! default => println!("the channel is empty"), //! } //! # } //! ``` //! //! ### How to try sending a message without blocking when the channel is full? //! //! Use the [`select!`] macro: //! //! ```rust //! # #[macro_use] //! # extern crate crossbeam_channel; //! # fn main() { //! use crossbeam_channel as channel; //! //! let (s, r) = channel::bounded(1); //! s.send("first"); //! //! select! { //! send(s, "second") => println!("message sent"), //! default => println!("the channel is full"), //! } //! # } //! ``` //! //! ### How to try sending/receiving a message with a timeout? //! //! Function [`after`] creates a special kind of channel that delivers a message after the //! specified timeout. Use [`select!`] to wait until a message is sent/received or the timeout //! is fired: //! //! //! ```rust //! # #[macro_use] //! # extern crate crossbeam_channel; //! # fn main() { //! use std::time::Duration; //! use crossbeam_channel as channel; //! //! let (s, r) = channel::bounded(1); //! s.send("hello"); //! //! let timeout = Duration::from_millis(100); //! //! select! { //! recv(r, msg) => match msg { //! Some(msg) => println!("received {:?}", msg), //! None => println!("the channel is closed"), //! } //! recv(channel::after(timeout)) => println!("timed out; the channel is still empty"), //! } //! # } //! ``` //! //! [`std::sync::mpsc`]: https://doc.rust-lang.org/std/sync/mpsc/index.html //! [`unbounded`]: fn.unbounded.html //! [`bounded`]: fn.bounded.html //! [`after`]: fn.bounded.html //! [`send`]: struct.Sender.html#method.send //! [`try_recv`]: struct.Receiver.html#method.try_recv //! [`recv`]: struct.Receiver.html#method.recv //! [`next`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next //! [`Iterator`]: https://doc.rust-lang.org/std/iter/trait.Iterator.html //! [`select!`]: macro.select.html //! [`Select`]: struct.Select.html //! [`Sender`]: struct.Sender.html //! [`Receiver`]: struct.Receiver.html extern crate crossbeam_epoch; extern crate crossbeam_utils; extern crate rand; extern crate parking_lot; mod flavors; #[doc(hidden)] pub mod internal; pub use internal::channel::{Receiver, Sender}; pub use internal::channel::{bounded, unbounded}; pub use internal::channel::{after, tick}; pub use internal::select::Select;