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