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