std/sync/mpsc.rs
1//! Multi-producer, single-consumer FIFO queue communication primitives.
2//!
3//! This module provides message-based communication over channels, concretely
4//! defined among three types:
5//!
6//! * [`Sender`]
7//! * [`SyncSender`]
8//! * [`Receiver`]
9//!
10//! A [`Sender`] or [`SyncSender`] is used to send data to a [`Receiver`]. Both
11//! senders are clone-able (multi-producer) such that many threads can send
12//! simultaneously to one receiver (single-consumer).
13//!
14//! These channels come in two flavors:
15//!
16//! 1. An asynchronous, infinitely buffered channel. The [`channel`] function
17//! will return a `(Sender, Receiver)` tuple where all sends will be
18//! **asynchronous** (they never block for space to become available; see
19//! [`std::sync`] for precise guarantees on blocking.) The channel
20//! conceptually has an infinite buffer.
21//!
22//! 2. A synchronous, bounded channel. The [`sync_channel`] function will
23//! return a `(SyncSender, Receiver)` tuple where the storage for pending
24//! messages is a pre-allocated buffer of a fixed size. All sends will be
25//! **synchronous** by blocking until there is buffer space available. Note
26//! that a bound of 0 is allowed, causing the channel to become a "rendezvous"
27//! channel where each sender atomically hands off a message to a receiver.
28//!
29//! [`send`]: Sender::send
30//! [`std::sync`]: ../index.html#blocking-guarantees
31//!
32//! ## Disconnection
33//!
34//! The send and receive operations on channels will all return a [`Result`]
35//! indicating whether the operation succeeded or not. An unsuccessful operation
36//! is normally indicative of the other half of a channel having "hung up" by
37//! being dropped in its corresponding thread.
38//!
39//! Once half of a channel has been deallocated, most operations can no longer
40//! continue to make progress, so [`Err`] will be returned. Many applications
41//! will continue to [`unwrap`] the results returned from this module,
42//! instigating a propagation of failure among threads if one unexpectedly dies.
43//!
44//! [`unwrap`]: Result::unwrap
45//!
46//! # Examples
47//!
48//! Simple usage:
49//!
50//! ```
51//! use std::thread;
52//! use std::sync::mpsc::channel;
53//!
54//! // Create a simple streaming channel
55//! let (tx, rx) = channel();
56//! thread::spawn(move || {
57//! tx.send(10).unwrap();
58//! });
59//! assert_eq!(rx.recv().unwrap(), 10);
60//! ```
61//!
62//! Shared usage:
63//!
64//! ```
65//! use std::thread;
66//! use std::sync::mpsc::channel;
67//!
68//! // Create a shared channel that can be sent along from many threads
69//! // where tx is the sending half (tx for transmission), and rx is the receiving
70//! // half (rx for receiving).
71//! let (tx, rx) = channel();
72//! for i in 0..10 {
73//! let tx = tx.clone();
74//! thread::spawn(move || {
75//! tx.send(i).unwrap();
76//! });
77//! }
78//!
79//! for _ in 0..10 {
80//! let j = rx.recv().unwrap();
81//! assert!(0 <= j && j < 10);
82//! }
83//! ```
84//!
85//! Propagating panics:
86//!
87//! ```
88//! use std::sync::mpsc::channel;
89//!
90//! // The call to recv() will return an error because the channel has already
91//! // hung up (or been deallocated)
92//! let (tx, rx) = channel::<i32>();
93//! drop(tx);
94//! assert!(rx.recv().is_err());
95//! ```
96//!
97//! Synchronous channels:
98//!
99//! ```
100//! use std::thread;
101//! use std::sync::mpsc::sync_channel;
102//!
103//! let (tx, rx) = sync_channel::<i32>(0);
104//! thread::spawn(move || {
105//! // This will wait for the parent thread to start receiving
106//! tx.send(53).unwrap();
107//! });
108//! rx.recv().unwrap();
109//! ```
110//!
111//! Unbounded receive loop:
112//!
113//! ```
114//! use std::sync::mpsc::sync_channel;
115//! use std::thread;
116//!
117//! let (tx, rx) = sync_channel(3);
118//!
119//! for _ in 0..3 {
120//! // It would be the same without thread and clone here
121//! // since there will still be one `tx` left.
122//! let tx = tx.clone();
123//! // cloned tx dropped within thread
124//! thread::spawn(move || tx.send("ok").unwrap());
125//! }
126//!
127//! // Drop the last sender to stop `rx` waiting for message.
128//! // The program will not complete if we comment this out.
129//! // **All** `tx` needs to be dropped for `rx` to have `Err`.
130//! drop(tx);
131//!
132//! // Unbounded receiver waiting for all senders to complete.
133//! while let Ok(msg) = rx.recv() {
134//! println!("{msg}");
135//! }
136//!
137//! println!("completed");
138//! ```
139
140#![stable(feature = "rust1", since = "1.0.0")]
141
142// MPSC channels are built as a wrapper around MPMC channels, which
143// were ported from the `crossbeam-channel` crate. MPMC channels are
144// not exposed publicly, but if you are curious about the implementation,
145// that's where everything is.
146
147use core::clone::Share;
148
149use crate::sync::mpmc;
150use crate::time::{Duration, Instant};
151use crate::{error, fmt};
152
153/// The receiving half of Rust's [`channel`] (or [`sync_channel`]) type.
154/// This half can only be owned by one thread.
155///
156/// Messages sent to the channel can be retrieved using [`recv`].
157///
158/// [`recv`]: Receiver::recv
159///
160/// # Examples
161///
162/// ```rust
163/// use std::sync::mpsc::channel;
164/// use std::thread;
165/// use std::time::Duration;
166///
167/// let (send, recv) = channel();
168///
169/// thread::spawn(move || {
170/// send.send("Hello world!").unwrap();
171/// thread::sleep(Duration::from_secs(2)); // block for two seconds
172/// send.send("Delayed for 2 seconds").unwrap();
173/// });
174///
175/// println!("{}", recv.recv().unwrap()); // Received immediately
176/// println!("Waiting...");
177/// println!("{}", recv.recv().unwrap()); // Received after 2 seconds
178/// ```
179#[stable(feature = "rust1", since = "1.0.0")]
180#[cfg_attr(not(test), rustc_diagnostic_item = "MpscReceiver")]
181pub struct Receiver<T> {
182 inner: mpmc::Receiver<T>,
183}
184
185// The receiver port can be sent from place to place, so long as it
186// is not used to receive non-sendable things.
187#[stable(feature = "rust1", since = "1.0.0")]
188unsafe impl<T: Send> Send for Receiver<T> {}
189
190#[stable(feature = "rust1", since = "1.0.0")]
191impl<T> !Sync for Receiver<T> {}
192
193/// An iterator over messages on a [`Receiver`], created by [`iter`].
194///
195/// This iterator will block whenever [`next`] is called,
196/// waiting for a new message, and [`None`] will be returned
197/// when the corresponding channel has hung up.
198///
199/// [`iter`]: Receiver::iter
200/// [`next`]: Iterator::next
201///
202/// # Examples
203///
204/// ```rust
205/// use std::sync::mpsc::channel;
206/// use std::thread;
207///
208/// let (send, recv) = channel();
209///
210/// thread::spawn(move || {
211/// send.send(1u8).unwrap();
212/// send.send(2u8).unwrap();
213/// send.send(3u8).unwrap();
214/// });
215///
216/// for x in recv.iter() {
217/// println!("Got: {x}");
218/// }
219/// ```
220#[stable(feature = "rust1", since = "1.0.0")]
221#[derive(Debug)]
222pub struct Iter<'a, T: 'a> {
223 rx: &'a Receiver<T>,
224}
225
226/// An iterator that attempts to yield all pending values for a [`Receiver`],
227/// created by [`try_iter`].
228///
229/// [`None`] will be returned when there are no pending values remaining or
230/// if the corresponding channel has hung up.
231///
232/// This iterator will never block the caller in order to wait for data to
233/// become available. Instead, it will return [`None`]. (See [`std::sync`] for
234/// precise guarantees on blocking.)
235///
236/// [`try_iter`]: Receiver::try_iter
237/// [`std::sync`]: ../index.html#blocking-guarantees
238///
239/// # Examples
240///
241/// ```rust
242/// use std::sync::mpsc::channel;
243/// use std::thread;
244/// use std::time::Duration;
245///
246/// let (sender, receiver) = channel();
247///
248/// // Nothing is in the buffer yet
249/// assert!(receiver.try_iter().next().is_none());
250/// println!("Nothing in the buffer...");
251///
252/// thread::spawn(move || {
253/// sender.send(1).unwrap();
254/// sender.send(2).unwrap();
255/// sender.send(3).unwrap();
256/// });
257///
258/// println!("Going to sleep...");
259/// thread::sleep(Duration::from_secs(2)); // block for two seconds
260///
261/// for x in receiver.try_iter() {
262/// println!("Got: {x}");
263/// }
264/// ```
265#[stable(feature = "receiver_try_iter", since = "1.15.0")]
266#[derive(Debug)]
267pub struct TryIter<'a, T: 'a> {
268 rx: &'a Receiver<T>,
269}
270
271/// An owning iterator over messages on a [`Receiver`],
272/// created by [`into_iter`].
273///
274/// This iterator will block whenever [`next`]
275/// is called, waiting for a new message, and [`None`] will be
276/// returned if the corresponding channel has hung up.
277///
278/// [`into_iter`]: Receiver::into_iter
279/// [`next`]: Iterator::next
280///
281/// # Examples
282///
283/// ```rust
284/// use std::sync::mpsc::channel;
285/// use std::thread;
286///
287/// let (send, recv) = channel();
288///
289/// thread::spawn(move || {
290/// send.send(1u8).unwrap();
291/// send.send(2u8).unwrap();
292/// send.send(3u8).unwrap();
293/// });
294///
295/// for x in recv.into_iter() {
296/// println!("Got: {x}");
297/// }
298/// ```
299#[stable(feature = "receiver_into_iter", since = "1.1.0")]
300#[derive(Debug)]
301pub struct IntoIter<T> {
302 rx: Receiver<T>,
303}
304
305/// The sending-half of Rust's asynchronous [`channel`] type.
306///
307/// Messages can be sent through this channel with [`send`].
308///
309/// Note: all senders (the original and its clones) need to be dropped for the receiver
310/// to stop blocking to receive messages with [`Receiver::recv`].
311///
312/// [`send`]: Sender::send
313///
314/// # Examples
315///
316/// ```rust
317/// use std::sync::mpsc::channel;
318/// use std::thread;
319///
320/// let (sender, receiver) = channel();
321/// let sender2 = sender.clone();
322///
323/// // First thread owns sender
324/// thread::spawn(move || {
325/// sender.send(1).unwrap();
326/// });
327///
328/// // Second thread owns sender2
329/// thread::spawn(move || {
330/// sender2.send(2).unwrap();
331/// });
332///
333/// let msg = receiver.recv().unwrap();
334/// let msg2 = receiver.recv().unwrap();
335///
336/// assert_eq!(3, msg + msg2);
337/// ```
338#[stable(feature = "rust1", since = "1.0.0")]
339#[cfg_attr(not(test), rustc_diagnostic_item = "MpscSender")]
340pub struct Sender<T> {
341 inner: mpmc::Sender<T>,
342}
343
344// The send port can be sent from place to place, so long as it
345// is not used to send non-sendable things.
346#[stable(feature = "rust1", since = "1.0.0")]
347unsafe impl<T: Send> Send for Sender<T> {}
348
349#[stable(feature = "mpsc_sender_sync", since = "1.72.0")]
350unsafe impl<T: Send> Sync for Sender<T> {}
351
352/// The sending-half of Rust's synchronous [`sync_channel`] type.
353///
354/// Messages can be sent through this channel with [`send`] or [`try_send`].
355///
356/// [`send`] will block if there is no space in the internal buffer.
357///
358/// [`send`]: SyncSender::send
359/// [`try_send`]: SyncSender::try_send
360///
361/// # Examples
362///
363/// ```rust
364/// use std::sync::mpsc::sync_channel;
365/// use std::thread;
366///
367/// // Create a sync_channel with buffer size 2
368/// let (sync_sender, receiver) = sync_channel(2);
369/// let sync_sender2 = sync_sender.clone();
370///
371/// // First thread owns sync_sender
372/// thread::spawn(move || {
373/// sync_sender.send(1).unwrap();
374/// sync_sender.send(2).unwrap();
375/// });
376///
377/// // Second thread owns sync_sender2
378/// thread::spawn(move || {
379/// sync_sender2.send(3).unwrap();
380/// // thread will now block since the buffer is full
381/// println!("Thread unblocked!");
382/// });
383///
384/// let mut msg;
385///
386/// msg = receiver.recv().unwrap();
387/// println!("message {msg} received");
388///
389/// // "Thread unblocked!" will be printed now
390///
391/// msg = receiver.recv().unwrap();
392/// println!("message {msg} received");
393///
394/// msg = receiver.recv().unwrap();
395///
396/// println!("message {msg} received");
397/// ```
398#[stable(feature = "rust1", since = "1.0.0")]
399pub struct SyncSender<T> {
400 inner: mpmc::Sender<T>,
401}
402
403#[stable(feature = "rust1", since = "1.0.0")]
404unsafe impl<T: Send> Send for SyncSender<T> {}
405
406/// An error returned from the [`Sender::send`] or [`SyncSender::send`]
407/// function on **channel**s.
408///
409/// A **send** operation can only fail if the receiving end of a channel is
410/// disconnected, implying that the data could never be received. The error
411/// contains the data being sent as a payload so it can be recovered.
412#[stable(feature = "rust1", since = "1.0.0")]
413#[derive(PartialEq, Eq, Clone, Copy)]
414pub struct SendError<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
415
416/// An error returned from the [`recv`] function on a [`Receiver`].
417///
418/// The [`recv`] operation can only fail if the sending half of a
419/// [`channel`] (or [`sync_channel`]) is disconnected, implying that no further
420/// messages will ever be received.
421///
422/// [`recv`]: Receiver::recv
423#[derive(PartialEq, Eq, Clone, Copy, Debug)]
424#[stable(feature = "rust1", since = "1.0.0")]
425pub struct RecvError;
426
427/// This enumeration is the list of the possible reasons that [`try_recv`] could
428/// not return data when called. This can occur with both a [`channel`] and
429/// a [`sync_channel`].
430///
431/// [`try_recv`]: Receiver::try_recv
432#[derive(PartialEq, Eq, Clone, Copy, Debug)]
433#[stable(feature = "rust1", since = "1.0.0")]
434pub enum TryRecvError {
435 /// This **channel** is currently empty, but the **Sender**(s) have not yet
436 /// disconnected, so data may yet become available.
437 #[stable(feature = "rust1", since = "1.0.0")]
438 Empty,
439
440 /// The **channel**'s sending half has become disconnected, and there will
441 /// never be any more data received on it.
442 #[stable(feature = "rust1", since = "1.0.0")]
443 Disconnected,
444}
445
446/// This enumeration is the list of possible errors that made [`recv_timeout`]
447/// unable to return data when called. This can occur with both a [`channel`] and
448/// a [`sync_channel`].
449///
450/// [`recv_timeout`]: Receiver::recv_timeout
451#[derive(PartialEq, Eq, Clone, Copy, Debug)]
452#[stable(feature = "mpsc_recv_timeout", since = "1.12.0")]
453pub enum RecvTimeoutError {
454 /// This **channel** is currently empty, but the **Sender**(s) have not yet
455 /// disconnected, so data may yet become available.
456 #[stable(feature = "mpsc_recv_timeout", since = "1.12.0")]
457 Timeout,
458 /// The **channel**'s sending half has become disconnected, and there will
459 /// never be any more data received on it.
460 #[stable(feature = "mpsc_recv_timeout", since = "1.12.0")]
461 Disconnected,
462}
463
464/// This enumeration is the list of the possible error outcomes for the
465/// [`try_send`] method.
466///
467/// [`try_send`]: SyncSender::try_send
468#[stable(feature = "rust1", since = "1.0.0")]
469#[derive(PartialEq, Eq, Clone, Copy)]
470pub enum TrySendError<T> {
471 /// The data could not be sent on the [`sync_channel`] because it would require that
472 /// the callee block to send the data.
473 ///
474 /// If this is a buffered channel, then the buffer is full at this time. If
475 /// this is not a buffered channel, then there is no [`Receiver`] available to
476 /// acquire the data.
477 #[stable(feature = "rust1", since = "1.0.0")]
478 Full(#[stable(feature = "rust1", since = "1.0.0")] T),
479
480 /// This [`sync_channel`]'s receiving half has disconnected, so the data could not be
481 /// sent. The data is returned back to the callee in this case.
482 #[stable(feature = "rust1", since = "1.0.0")]
483 Disconnected(#[stable(feature = "rust1", since = "1.0.0")] T),
484}
485
486/// Creates a new asynchronous channel, returning the sender/receiver halves.
487///
488/// All data sent on the [`Sender`] will become available on the [`Receiver`] in
489/// the same order as it was sent, and no [`send`] will block the calling thread
490/// (this channel has an "infinite buffer", unlike [`sync_channel`], which will
491/// block after its buffer limit is reached). [`recv`] will block until a message
492/// is available while there is at least one [`Sender`] alive (including clones).
493///
494/// The [`Sender`] can be cloned to [`send`] to the same channel multiple times, but
495/// only one [`Receiver`] is supported.
496///
497/// If the [`Receiver`] is disconnected while trying to [`send`] with the
498/// [`Sender`], the [`send`] method will return a [`SendError`]. Similarly, if the
499/// [`Sender`] is disconnected while trying to [`recv`], the [`recv`] method will
500/// return a [`RecvError`].
501///
502/// [`send`]: Sender::send
503/// [`recv`]: Receiver::recv
504///
505/// # Examples
506///
507/// ```
508/// use std::sync::mpsc::channel;
509/// use std::thread;
510///
511/// let (sender, receiver) = channel();
512///
513/// // Spawn off an expensive computation
514/// thread::spawn(move || {
515/// # fn expensive_computation() {}
516/// sender.send(expensive_computation()).unwrap();
517/// });
518///
519/// // Do some useful work for a while
520///
521/// // Let's see what that answer was
522/// println!("{:?}", receiver.recv().unwrap());
523/// ```
524#[must_use]
525#[stable(feature = "rust1", since = "1.0.0")]
526pub fn channel<T>() -> (Sender<T>, Receiver<T>) {
527 let (tx, rx) = mpmc::channel();
528 (Sender { inner: tx }, Receiver { inner: rx })
529}
530
531/// Creates a new synchronous, bounded channel.
532///
533/// All data sent on the [`SyncSender`] will become available on the [`Receiver`]
534/// in the same order as it was sent. Like asynchronous [`channel`]s, the
535/// [`Receiver`] will block until a message becomes available. `sync_channel`
536/// differs greatly in the semantics of the sender, however.
537///
538/// This channel has an internal buffer on which messages will be queued.
539/// `bound` specifies the buffer size. When the internal buffer becomes full,
540/// future sends will *block* waiting for the buffer to open up. Note that a
541/// buffer size of 0 is valid, in which case this becomes "rendezvous channel"
542/// where each [`send`] will not return until a [`recv`] is paired with it.
543///
544/// The [`SyncSender`] can be cloned to [`send`] to the same channel multiple
545/// times, but only one [`Receiver`] is supported.
546///
547/// Like asynchronous channels, if the [`Receiver`] is disconnected while trying
548/// to [`send`] with the [`SyncSender`], the [`send`] method will return a
549/// [`SendError`]. Similarly, If the [`SyncSender`] is disconnected while trying
550/// to [`recv`], the [`recv`] method will return a [`RecvError`].
551///
552/// [`send`]: SyncSender::send
553/// [`recv`]: Receiver::recv
554///
555/// # Examples
556///
557/// ```
558/// use std::sync::mpsc::sync_channel;
559/// use std::thread;
560///
561/// let (sender, receiver) = sync_channel(1);
562///
563/// // this returns immediately
564/// sender.send(1).unwrap();
565///
566/// thread::spawn(move || {
567/// // this will block until the previous message has been received
568/// sender.send(2).unwrap();
569/// });
570///
571/// assert_eq!(receiver.recv().unwrap(), 1);
572/// assert_eq!(receiver.recv().unwrap(), 2);
573/// ```
574#[must_use]
575#[stable(feature = "rust1", since = "1.0.0")]
576pub fn sync_channel<T>(bound: usize) -> (SyncSender<T>, Receiver<T>) {
577 let (tx, rx) = mpmc::sync_channel(bound);
578 (SyncSender { inner: tx }, Receiver { inner: rx })
579}
580
581////////////////////////////////////////////////////////////////////////////////
582// Sender
583////////////////////////////////////////////////////////////////////////////////
584
585impl<T> Sender<T> {
586 /// Attempts to send a value on this channel, returning it back if it could
587 /// not be sent.
588 ///
589 /// A successful send occurs when it is determined that the other end of
590 /// the channel has not hung up already. An unsuccessful send would be one
591 /// where the corresponding receiver has already been deallocated. Note
592 /// that a return value of [`Err`] means that the data will never be
593 /// received, but a return value of [`Ok`] does *not* mean that the data
594 /// will be received. It is possible for the corresponding receiver to
595 /// hang up immediately after this function returns [`Ok`].
596 ///
597 /// This method will never block the caller in order to wait for space to
598 /// become available. (See [`std::sync`] for precise guarantees on blocking.)
599 ///
600 /// [`std::sync`]: ../index.html#blocking-guarantees
601 ///
602 /// # Examples
603 ///
604 /// ```
605 /// use std::sync::mpsc::channel;
606 ///
607 /// let (tx, rx) = channel();
608 ///
609 /// // This send is always successful
610 /// tx.send(1).unwrap();
611 ///
612 /// // This send will fail because the receiver is gone
613 /// drop(rx);
614 /// assert_eq!(tx.send(1).unwrap_err().0, 1);
615 /// ```
616 #[stable(feature = "rust1", since = "1.0.0")]
617 pub fn send(&self, t: T) -> Result<(), SendError<T>> {
618 self.inner.send(t)
619 }
620
621 /// Returns `true` if the channel is disconnected.
622 ///
623 /// Note that a return value of `false` does not guarantee the channel will
624 /// remain connected. The channel may be disconnected immediately after this method
625 /// returns, so a subsequent [`Sender::send`] may still fail with [`SendError`].
626 ///
627 /// # Examples
628 ///
629 /// ```
630 /// #![feature(mpsc_is_disconnected)]
631 ///
632 /// use std::sync::mpsc::channel;
633 ///
634 /// let (tx, rx) = channel::<i32>();
635 /// assert!(!tx.is_disconnected());
636 /// drop(rx);
637 /// assert!(tx.is_disconnected());
638 /// ```
639 #[unstable(feature = "mpsc_is_disconnected", issue = "153668")]
640 pub fn is_disconnected(&self) -> bool {
641 self.inner.is_disconnected()
642 }
643}
644
645#[stable(feature = "rust1", since = "1.0.0")]
646impl<T> Clone for Sender<T> {
647 /// Clone a sender to send to other threads.
648 ///
649 /// Note, be aware of the lifetime of the sender because all senders
650 /// (including the original) need to be dropped in order for
651 /// [`Receiver::recv`] to stop blocking.
652 fn clone(&self) -> Sender<T> {
653 Sender { inner: self.inner.clone() }
654 }
655}
656
657#[unstable(feature = "share_trait", issue = "156756")]
658impl<T> Share for Sender<T> {}
659
660#[stable(feature = "mpsc_debug", since = "1.8.0")]
661impl<T> fmt::Debug for Sender<T> {
662 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
663 f.debug_struct("Sender").finish_non_exhaustive()
664 }
665}
666
667////////////////////////////////////////////////////////////////////////////////
668// SyncSender
669////////////////////////////////////////////////////////////////////////////////
670
671impl<T> SyncSender<T> {
672 /// Sends a value on this synchronous channel.
673 ///
674 /// This function will *block* until space in the internal buffer becomes
675 /// available or a receiver is available to hand off the message to.
676 ///
677 /// Note that a successful send does *not* guarantee that the receiver will
678 /// ever see the data if there is a buffer on this channel. Items may be
679 /// enqueued in the internal buffer for the receiver to receive at a later
680 /// time. If the buffer size is 0, however, the channel becomes a rendezvous
681 /// channel and it guarantees that the receiver has indeed received
682 /// the data if this function returns success.
683 ///
684 /// This function will never panic, but it may return [`Err`] if the
685 /// [`Receiver`] has disconnected and is no longer able to receive
686 /// information.
687 ///
688 /// # Examples
689 ///
690 /// ```rust
691 /// use std::sync::mpsc::sync_channel;
692 /// use std::thread;
693 ///
694 /// // Create a rendezvous sync_channel with buffer size 0
695 /// let (sync_sender, receiver) = sync_channel(0);
696 ///
697 /// thread::spawn(move || {
698 /// println!("sending message...");
699 /// sync_sender.send(1).unwrap();
700 /// // Thread is now blocked until the message is received
701 ///
702 /// println!("...message received!");
703 /// });
704 ///
705 /// let msg = receiver.recv().unwrap();
706 /// assert_eq!(1, msg);
707 /// ```
708 #[stable(feature = "rust1", since = "1.0.0")]
709 pub fn send(&self, t: T) -> Result<(), SendError<T>> {
710 self.inner.send(t)
711 }
712
713 /// Attempts to send a value on this channel without blocking.
714 ///
715 /// This method differs from [`send`] by returning immediately if the
716 /// channel's buffer is full or no receiver is waiting to acquire some
717 /// data. Compared with [`send`], this function has two failure cases
718 /// instead of one (one for disconnection, one for a full buffer).
719 ///
720 /// See [`send`] for notes about guarantees of whether the
721 /// receiver has received the data or not if this function is successful.
722 ///
723 /// [`send`]: Self::send
724 ///
725 /// # Examples
726 ///
727 /// ```rust
728 /// use std::sync::mpsc::sync_channel;
729 /// use std::thread;
730 ///
731 /// // Create a sync_channel with buffer size 1
732 /// let (sync_sender, receiver) = sync_channel(1);
733 /// let sync_sender2 = sync_sender.clone();
734 ///
735 /// // First thread owns sync_sender
736 /// let handle1 = thread::spawn(move || {
737 /// sync_sender.send(1).unwrap();
738 /// sync_sender.send(2).unwrap();
739 /// // Thread blocked
740 /// });
741 ///
742 /// // Second thread owns sync_sender2
743 /// let handle2 = thread::spawn(move || {
744 /// // This will return an error and send
745 /// // no message if the buffer is full
746 /// let _ = sync_sender2.try_send(3);
747 /// });
748 ///
749 /// let mut msg;
750 /// msg = receiver.recv().unwrap();
751 /// println!("message {msg} received");
752 ///
753 /// msg = receiver.recv().unwrap();
754 /// println!("message {msg} received");
755 ///
756 /// // Third message may have never been sent
757 /// match receiver.try_recv() {
758 /// Ok(msg) => println!("message {msg} received"),
759 /// Err(_) => println!("the third message was never sent"),
760 /// }
761 ///
762 /// // Wait for threads to complete
763 /// handle1.join().unwrap();
764 /// handle2.join().unwrap();
765 /// ```
766 #[stable(feature = "rust1", since = "1.0.0")]
767 pub fn try_send(&self, t: T) -> Result<(), TrySendError<T>> {
768 self.inner.try_send(t)
769 }
770
771 // Attempts to send for a value on this receiver, returning an error if the
772 // corresponding channel has hung up, or if it waits more than `timeout`.
773 //
774 // This method is currently only used for tests.
775 #[unstable(issue = "none", feature = "std_internals")]
776 #[doc(hidden)]
777 pub fn send_timeout(&self, t: T, timeout: Duration) -> Result<(), mpmc::SendTimeoutError<T>> {
778 self.inner.send_timeout(t, timeout)
779 }
780}
781
782#[stable(feature = "rust1", since = "1.0.0")]
783impl<T> Clone for SyncSender<T> {
784 fn clone(&self) -> SyncSender<T> {
785 SyncSender { inner: self.inner.clone() }
786 }
787}
788
789#[unstable(feature = "share_trait", issue = "156756")]
790impl<T> Share for SyncSender<T> {}
791
792#[stable(feature = "mpsc_debug", since = "1.8.0")]
793impl<T> fmt::Debug for SyncSender<T> {
794 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
795 f.debug_struct("SyncSender").finish_non_exhaustive()
796 }
797}
798
799////////////////////////////////////////////////////////////////////////////////
800// Receiver
801////////////////////////////////////////////////////////////////////////////////
802
803impl<T> Receiver<T> {
804 /// Attempts to return a pending value on this receiver without blocking.
805 ///
806 /// This method will never block the caller in order to wait for data to
807 /// become available. Instead, this will always return immediately with a
808 /// possible option of pending data on the channel. (See [`std::sync`] for
809 /// precise guarantees on blocking.)
810 ///
811 /// This is useful for a flavor of "optimistic check" before deciding to
812 /// block on a receiver.
813 ///
814 /// Compared with [`recv`], this function has two failure cases instead of one
815 /// (one for disconnection, one for an empty buffer).
816 ///
817 /// [`recv`]: Self::recv
818 /// [`std::sync`]: ../index.html#blocking-guarantees
819 ///
820 /// # Examples
821 ///
822 /// ```rust
823 /// use std::sync::mpsc::{Receiver, channel};
824 ///
825 /// let (_, receiver): (_, Receiver<i32>) = channel();
826 ///
827 /// assert!(receiver.try_recv().is_err());
828 /// ```
829 #[stable(feature = "rust1", since = "1.0.0")]
830 pub fn try_recv(&self) -> Result<T, TryRecvError> {
831 self.inner.try_recv()
832 }
833
834 /// Attempts to wait for a value on this receiver, returning an error if the
835 /// corresponding channel has hung up.
836 ///
837 /// This function will always block the current thread if there is no data
838 /// available and it's possible for more data to be sent (at least one sender
839 /// still exists). Once a message is sent to the corresponding [`Sender`]
840 /// (or [`SyncSender`]), this receiver will wake up and return that
841 /// message.
842 ///
843 /// If the corresponding [`Sender`] has disconnected, or it disconnects while
844 /// this call is blocking, this call will wake up and return [`Err`] to
845 /// indicate that no more messages can ever be received on this channel.
846 /// However, since channels are buffered, messages sent before the disconnect
847 /// will still be properly received.
848 ///
849 /// # Examples
850 ///
851 /// ```
852 /// use std::sync::mpsc;
853 /// use std::thread;
854 ///
855 /// let (send, recv) = mpsc::channel();
856 /// let handle = thread::spawn(move || {
857 /// send.send(1u8).unwrap();
858 /// });
859 ///
860 /// handle.join().unwrap();
861 ///
862 /// assert_eq!(Ok(1), recv.recv());
863 /// ```
864 ///
865 /// Buffering behavior:
866 ///
867 /// ```
868 /// use std::sync::mpsc;
869 /// use std::thread;
870 /// use std::sync::mpsc::RecvError;
871 ///
872 /// let (send, recv) = mpsc::channel();
873 /// let handle = thread::spawn(move || {
874 /// send.send(1u8).unwrap();
875 /// send.send(2).unwrap();
876 /// send.send(3).unwrap();
877 /// drop(send);
878 /// });
879 ///
880 /// // wait for the thread to join so we ensure the sender is dropped
881 /// handle.join().unwrap();
882 ///
883 /// assert_eq!(Ok(1), recv.recv());
884 /// assert_eq!(Ok(2), recv.recv());
885 /// assert_eq!(Ok(3), recv.recv());
886 /// assert_eq!(Err(RecvError), recv.recv());
887 /// ```
888 #[stable(feature = "rust1", since = "1.0.0")]
889 pub fn recv(&self) -> Result<T, RecvError> {
890 self.inner.recv()
891 }
892
893 /// Attempts to wait for a value on this receiver, returning an error if the
894 /// corresponding channel has hung up, or if it waits more than `timeout`.
895 ///
896 /// This function will always block the current thread if there is no data
897 /// available and it's possible for more data to be sent (at least one sender
898 /// still exists). Once a message is sent to the corresponding [`Sender`]
899 /// (or [`SyncSender`]), this receiver will wake up and return that
900 /// message.
901 ///
902 /// If the corresponding [`Sender`] has disconnected, or it disconnects while
903 /// this call is blocking, this call will wake up and return [`Err`] to
904 /// indicate that no more messages can ever be received on this channel.
905 /// However, since channels are buffered, messages sent before the disconnect
906 /// will still be properly received.
907 ///
908 /// # Examples
909 ///
910 /// Successfully receiving value before encountering timeout:
911 ///
912 /// ```no_run
913 /// use std::thread;
914 /// use std::time::Duration;
915 /// use std::sync::mpsc;
916 ///
917 /// let (send, recv) = mpsc::channel();
918 ///
919 /// thread::spawn(move || {
920 /// send.send('a').unwrap();
921 /// });
922 ///
923 /// assert_eq!(
924 /// recv.recv_timeout(Duration::from_millis(400)),
925 /// Ok('a')
926 /// );
927 /// ```
928 ///
929 /// Receiving an error upon reaching timeout:
930 ///
931 /// ```no_run
932 /// use std::thread;
933 /// use std::time::Duration;
934 /// use std::sync::mpsc;
935 ///
936 /// let (send, recv) = mpsc::channel();
937 ///
938 /// thread::spawn(move || {
939 /// thread::sleep(Duration::from_millis(800));
940 /// send.send('a').unwrap();
941 /// });
942 ///
943 /// assert_eq!(
944 /// recv.recv_timeout(Duration::from_millis(400)),
945 /// Err(mpsc::RecvTimeoutError::Timeout)
946 /// );
947 /// ```
948 #[stable(feature = "mpsc_recv_timeout", since = "1.12.0")]
949 pub fn recv_timeout(&self, timeout: Duration) -> Result<T, RecvTimeoutError> {
950 self.inner.recv_timeout(timeout)
951 }
952
953 /// Attempts to wait for a value on this receiver, returning an error if the
954 /// corresponding channel has hung up, or if `deadline` is reached.
955 ///
956 /// This function will always block the current thread if there is no data
957 /// available and it's possible for more data to be sent. Once a message is
958 /// sent to the corresponding [`Sender`] (or [`SyncSender`]), then this
959 /// receiver will wake up and return that message.
960 ///
961 /// If the corresponding [`Sender`] has disconnected, or it disconnects while
962 /// this call is blocking, this call will wake up and return [`Err`] to
963 /// indicate that no more messages can ever be received on this channel.
964 /// However, since channels are buffered, messages sent before the disconnect
965 /// will still be properly received.
966 ///
967 /// # Examples
968 ///
969 /// Successfully receiving value before reaching deadline:
970 ///
971 /// ```no_run
972 /// #![feature(deadline_api)]
973 /// use std::thread;
974 /// use std::time::{Duration, Instant};
975 /// use std::sync::mpsc;
976 ///
977 /// let (send, recv) = mpsc::channel();
978 ///
979 /// thread::spawn(move || {
980 /// send.send('a').unwrap();
981 /// });
982 ///
983 /// assert_eq!(
984 /// recv.recv_deadline(Instant::now() + Duration::from_millis(400)),
985 /// Ok('a')
986 /// );
987 /// ```
988 ///
989 /// Receiving an error upon reaching deadline:
990 ///
991 /// ```no_run
992 /// #![feature(deadline_api)]
993 /// use std::thread;
994 /// use std::time::{Duration, Instant};
995 /// use std::sync::mpsc;
996 ///
997 /// let (send, recv) = mpsc::channel();
998 ///
999 /// thread::spawn(move || {
1000 /// thread::sleep(Duration::from_millis(800));
1001 /// send.send('a').unwrap();
1002 /// });
1003 ///
1004 /// assert_eq!(
1005 /// recv.recv_deadline(Instant::now() + Duration::from_millis(400)),
1006 /// Err(mpsc::RecvTimeoutError::Timeout)
1007 /// );
1008 /// ```
1009 #[unstable(feature = "deadline_api", issue = "46316")]
1010 pub fn recv_deadline(&self, deadline: Instant) -> Result<T, RecvTimeoutError> {
1011 self.inner.recv_deadline(deadline)
1012 }
1013
1014 /// Returns an iterator that will block waiting for messages, but never
1015 /// [`panic!`]. It will return [`None`] when the channel has hung up.
1016 ///
1017 /// # Examples
1018 ///
1019 /// ```rust
1020 /// use std::sync::mpsc::channel;
1021 /// use std::thread;
1022 ///
1023 /// let (send, recv) = channel();
1024 ///
1025 /// thread::spawn(move || {
1026 /// send.send(1).unwrap();
1027 /// send.send(2).unwrap();
1028 /// send.send(3).unwrap();
1029 /// });
1030 ///
1031 /// let mut iter = recv.iter();
1032 /// assert_eq!(iter.next(), Some(1));
1033 /// assert_eq!(iter.next(), Some(2));
1034 /// assert_eq!(iter.next(), Some(3));
1035 /// assert_eq!(iter.next(), None);
1036 /// ```
1037 #[stable(feature = "rust1", since = "1.0.0")]
1038 pub fn iter(&self) -> Iter<'_, T> {
1039 Iter { rx: self }
1040 }
1041
1042 /// Returns an iterator that will attempt to yield all pending values.
1043 /// It will return `None` if there are no more pending values or if the
1044 /// channel has hung up. The iterator will never [`panic!`] or block the
1045 /// user by waiting for values.
1046 ///
1047 /// # Examples
1048 ///
1049 /// ```no_run
1050 /// use std::sync::mpsc::channel;
1051 /// use std::thread;
1052 /// use std::time::Duration;
1053 ///
1054 /// let (sender, receiver) = channel();
1055 ///
1056 /// // nothing is in the buffer yet
1057 /// assert!(receiver.try_iter().next().is_none());
1058 ///
1059 /// thread::spawn(move || {
1060 /// thread::sleep(Duration::from_secs(1));
1061 /// sender.send(1).unwrap();
1062 /// sender.send(2).unwrap();
1063 /// sender.send(3).unwrap();
1064 /// });
1065 ///
1066 /// // nothing is in the buffer yet
1067 /// assert!(receiver.try_iter().next().is_none());
1068 ///
1069 /// // block for two seconds
1070 /// thread::sleep(Duration::from_secs(2));
1071 ///
1072 /// let mut iter = receiver.try_iter();
1073 /// assert_eq!(iter.next(), Some(1));
1074 /// assert_eq!(iter.next(), Some(2));
1075 /// assert_eq!(iter.next(), Some(3));
1076 /// assert_eq!(iter.next(), None);
1077 /// ```
1078 #[stable(feature = "receiver_try_iter", since = "1.15.0")]
1079 pub fn try_iter(&self) -> TryIter<'_, T> {
1080 TryIter { rx: self }
1081 }
1082
1083 /// Returns `true` if the channel is disconnected.
1084 ///
1085 /// Note that a return value of `false` does not guarantee the channel will
1086 /// remain connected. The channel may be disconnected immediately after this method
1087 /// returns, so a subsequent [`Receiver::recv`] may still fail with [`RecvError`].
1088 ///
1089 /// # Examples
1090 ///
1091 /// ```
1092 /// #![feature(mpsc_is_disconnected)]
1093 ///
1094 /// use std::sync::mpsc::channel;
1095 ///
1096 /// let (tx, rx) = channel::<i32>();
1097 /// assert!(!rx.is_disconnected());
1098 /// drop(tx);
1099 /// assert!(rx.is_disconnected());
1100 /// ```
1101 #[unstable(feature = "mpsc_is_disconnected", issue = "153668")]
1102 pub fn is_disconnected(&self) -> bool {
1103 self.inner.is_disconnected()
1104 }
1105}
1106
1107#[stable(feature = "rust1", since = "1.0.0")]
1108impl<'a, T> Iterator for Iter<'a, T> {
1109 type Item = T;
1110
1111 fn next(&mut self) -> Option<T> {
1112 self.rx.recv().ok()
1113 }
1114}
1115
1116#[stable(feature = "receiver_try_iter", since = "1.15.0")]
1117impl<'a, T> Iterator for TryIter<'a, T> {
1118 type Item = T;
1119
1120 fn next(&mut self) -> Option<T> {
1121 self.rx.try_recv().ok()
1122 }
1123}
1124
1125#[stable(feature = "receiver_into_iter", since = "1.1.0")]
1126impl<'a, T> IntoIterator for &'a Receiver<T> {
1127 type Item = T;
1128 type IntoIter = Iter<'a, T>;
1129
1130 fn into_iter(self) -> Iter<'a, T> {
1131 self.iter()
1132 }
1133}
1134
1135#[stable(feature = "receiver_into_iter", since = "1.1.0")]
1136impl<T> Iterator for IntoIter<T> {
1137 type Item = T;
1138 fn next(&mut self) -> Option<T> {
1139 self.rx.recv().ok()
1140 }
1141}
1142
1143#[stable(feature = "receiver_into_iter", since = "1.1.0")]
1144impl<T> IntoIterator for Receiver<T> {
1145 type Item = T;
1146 type IntoIter = IntoIter<T>;
1147
1148 fn into_iter(self) -> IntoIter<T> {
1149 IntoIter { rx: self }
1150 }
1151}
1152
1153#[stable(feature = "mpsc_debug", since = "1.8.0")]
1154impl<T> fmt::Debug for Receiver<T> {
1155 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1156 f.debug_struct("Receiver").finish_non_exhaustive()
1157 }
1158}
1159
1160#[stable(feature = "rust1", since = "1.0.0")]
1161impl<T> fmt::Debug for SendError<T> {
1162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1163 f.debug_struct("SendError").finish_non_exhaustive()
1164 }
1165}
1166
1167#[stable(feature = "rust1", since = "1.0.0")]
1168impl<T> fmt::Display for SendError<T> {
1169 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1170 "sending on a closed channel".fmt(f)
1171 }
1172}
1173
1174#[stable(feature = "rust1", since = "1.0.0")]
1175impl<T> error::Error for SendError<T> {}
1176
1177#[stable(feature = "rust1", since = "1.0.0")]
1178impl<T> fmt::Debug for TrySendError<T> {
1179 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1180 match *self {
1181 TrySendError::Full(..) => f.debug_tuple("TrySendError::Full").finish_non_exhaustive(),
1182 TrySendError::Disconnected(..) => {
1183 f.debug_tuple("TrySendError::Disconnected").finish_non_exhaustive()
1184 }
1185 }
1186 }
1187}
1188
1189#[stable(feature = "rust1", since = "1.0.0")]
1190impl<T> fmt::Display for TrySendError<T> {
1191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1192 match *self {
1193 TrySendError::Full(..) => "sending on a full channel".fmt(f),
1194 TrySendError::Disconnected(..) => "sending on a closed channel".fmt(f),
1195 }
1196 }
1197}
1198
1199#[stable(feature = "rust1", since = "1.0.0")]
1200impl<T> error::Error for TrySendError<T> {}
1201
1202#[stable(feature = "mpsc_error_conversions", since = "1.24.0")]
1203impl<T> From<SendError<T>> for TrySendError<T> {
1204 /// Converts a `SendError<T>` into a `TrySendError<T>`.
1205 ///
1206 /// This conversion always returns a `TrySendError::Disconnected` containing the data in the `SendError<T>`.
1207 ///
1208 /// No data is allocated on the heap.
1209 fn from(err: SendError<T>) -> TrySendError<T> {
1210 match err {
1211 SendError(t) => TrySendError::Disconnected(t),
1212 }
1213 }
1214}
1215
1216#[stable(feature = "rust1", since = "1.0.0")]
1217impl fmt::Display for RecvError {
1218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1219 "receiving on a closed channel".fmt(f)
1220 }
1221}
1222
1223#[stable(feature = "rust1", since = "1.0.0")]
1224impl error::Error for RecvError {}
1225
1226#[stable(feature = "rust1", since = "1.0.0")]
1227impl fmt::Display for TryRecvError {
1228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1229 match *self {
1230 TryRecvError::Empty => "receiving on an empty channel".fmt(f),
1231 TryRecvError::Disconnected => "receiving on a closed channel".fmt(f),
1232 }
1233 }
1234}
1235
1236#[stable(feature = "rust1", since = "1.0.0")]
1237impl error::Error for TryRecvError {}
1238
1239#[stable(feature = "mpsc_error_conversions", since = "1.24.0")]
1240impl From<RecvError> for TryRecvError {
1241 /// Converts a `RecvError` into a `TryRecvError`.
1242 ///
1243 /// This conversion always returns `TryRecvError::Disconnected`.
1244 ///
1245 /// No data is allocated on the heap.
1246 fn from(err: RecvError) -> TryRecvError {
1247 match err {
1248 RecvError => TryRecvError::Disconnected,
1249 }
1250 }
1251}
1252
1253#[stable(feature = "mpsc_recv_timeout_error", since = "1.15.0")]
1254impl fmt::Display for RecvTimeoutError {
1255 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1256 match *self {
1257 RecvTimeoutError::Timeout => "timed out waiting on channel".fmt(f),
1258 RecvTimeoutError::Disconnected => "channel is empty and sending half is closed".fmt(f),
1259 }
1260 }
1261}
1262
1263#[stable(feature = "mpsc_recv_timeout_error", since = "1.15.0")]
1264impl error::Error for RecvTimeoutError {}
1265
1266#[stable(feature = "mpsc_error_conversions", since = "1.24.0")]
1267impl From<RecvError> for RecvTimeoutError {
1268 /// Converts a `RecvError` into a `RecvTimeoutError`.
1269 ///
1270 /// This conversion always returns `RecvTimeoutError::Disconnected`.
1271 ///
1272 /// No data is allocated on the heap.
1273 fn from(err: RecvError) -> RecvTimeoutError {
1274 match err {
1275 RecvError => RecvTimeoutError::Disconnected,
1276 }
1277 }
1278}