tokio/sync/broadcast.rs
1//! A multi-producer, multi-consumer broadcast queue. Each sent value is seen by
2//! all consumers.
3//!
4//! A [`Sender`] is used to broadcast values to **all** connected [`Receiver`]
5//! values. [`Sender`] handles are clone-able, allowing concurrent send and
6//! receive actions. [`Sender`] and [`Receiver`] are both `Send` and `Sync` as
7//! long as `T` is `Send`.
8//!
9//! When a value is sent, **all** [`Receiver`] handles are notified and will
10//! receive the value. The value is stored once inside the channel and cloned on
11//! demand for each receiver. Once all receivers have received a clone of the
12//! value, the value is released from the channel.
13//!
14//! A channel is created by calling [`channel`], specifying the maximum number
15//! of messages the channel can retain at any given time.
16//!
17//! New [`Receiver`] handles are created by calling [`Sender::subscribe`]. The
18//! returned [`Receiver`] will receive values sent **after** the call to
19//! `subscribe`.
20//!
21//! This channel is also suitable for the single-producer multi-consumer
22//! use-case, where a single sender broadcasts values to many receivers.
23//!
24//! ## Lagging
25//!
26//! As sent messages must be retained until **all** [`Receiver`] handles receive
27//! a clone, broadcast channels are susceptible to the "slow receiver" problem.
28//! In this case, all but one receiver are able to receive values at the rate
29//! they are sent. Because one receiver is stalled, the channel starts to fill
30//! up.
31//!
32//! This broadcast channel implementation handles this case by setting a hard
33//! upper bound on the number of values the channel may retain at any given
34//! time. This upper bound is passed to the [`channel`] function as an argument.
35//! The provided capacity is rounded **up** to the next power of two; that
36//! rounded size is the number of messages the ring buffer can hold, and is what
37//! lag detection is based on. For example, `channel(3)` allocates a buffer of
38//! length 4, so a receiver only lags once it falls more than 4 messages behind
39//! the sender.
40//!
41//! If a value is sent when the channel is at capacity, the oldest value
42//! currently held by the channel is overwritten. This frees up space for the
43//! new value. Any receiver that has not yet seen the overwritten value will
44//! return [`RecvError::Lagged`] the next time [`recv`] (or
45//! [`try_recv`](Receiver::try_recv)) is called. The error carries the number of
46//! messages that were dropped before the receiver's cursor and are therefore
47//! no longer available.
48//!
49//! Returning [`RecvError::Lagged`] does **not** close or disconnect the
50//! receiver. The lagging receiver's internal cursor is advanced to the oldest
51//! value still retained by the channel. The **next** successful call to
52//! [`recv`] / [`try_recv`](Receiver::try_recv) returns that oldest retained
53//! value (unless further sends overwrite it again before the receiver reads
54//! it). Subsequent receives then continue in send order from there.
55//!
56//! This behavior enables a receiver to detect when it has lagged so far behind
57//! that data has been dropped. The caller may decide how to respond to this:
58//! either by aborting its task or by tolerating lost messages and resuming
59//! consumption of the channel.
60//!
61//! ## Closing
62//!
63//! When **all** [`Sender`] handles have been dropped, no new values may be
64//! sent. At this point, the channel is "closed". Once a receiver has received
65//! all values retained by the channel, the next call to [`recv`] will return
66//! with [`RecvError::Closed`].
67//!
68//! When a [`Receiver`] handle is dropped, any messages not read by the receiver
69//! will be marked as read. If this receiver was the only one not to have read
70//! that message, the message will be dropped at this point.
71//!
72//! [`Sender`]: crate::sync::broadcast::Sender
73//! [`Sender::subscribe`]: crate::sync::broadcast::Sender::subscribe
74//! [`Receiver`]: crate::sync::broadcast::Receiver
75//! [`channel`]: crate::sync::broadcast::channel
76//! [`RecvError::Lagged`]: crate::sync::broadcast::error::RecvError::Lagged
77//! [`RecvError::Closed`]: crate::sync::broadcast::error::RecvError::Closed
78//! [`recv`]: crate::sync::broadcast::Receiver::recv
79//!
80//! # Examples
81//!
82//! Basic usage
83//!
84//! ```
85//! use tokio::sync::broadcast;
86//!
87//! # #[tokio::main(flavor = "current_thread")]
88//! # async fn main() {
89//! let (tx, mut rx1) = broadcast::channel(16);
90//! let mut rx2 = tx.subscribe();
91//!
92//! tokio::spawn(async move {
93//! assert_eq!(rx1.recv().await.unwrap(), 10);
94//! assert_eq!(rx1.recv().await.unwrap(), 20);
95//! });
96//!
97//! tokio::spawn(async move {
98//! assert_eq!(rx2.recv().await.unwrap(), 10);
99//! assert_eq!(rx2.recv().await.unwrap(), 20);
100//! });
101//!
102//! tx.send(10).unwrap();
103//! tx.send(20).unwrap();
104//! # }
105//! ```
106//!
107//! Handling lag
108//!
109//! ```
110//! use tokio::sync::broadcast;
111//! use tokio::sync::broadcast::error::RecvError;
112//!
113//! # #[tokio::main(flavor = "current_thread")]
114//! # async fn main() {
115//! // Capacity 2 → ring buffer of length 2.
116//! let (tx, mut rx) = broadcast::channel(2);
117//!
118//! tx.send(10).unwrap();
119//! tx.send(20).unwrap();
120//! // Overwrites 10; receiver has not read it yet.
121//! tx.send(30).unwrap();
122//!
123//! // One message (10) was dropped; cursor moves to the oldest retained value (20).
124//! assert!(matches!(rx.recv().await, Err(RecvError::Lagged(1))));
125//!
126//! // At this point, we can abort or continue with lost messages.
127//! // Continuing resumes from the oldest retained message.
128//! assert_eq!(20, rx.recv().await.unwrap());
129//! assert_eq!(30, rx.recv().await.unwrap());
130//! # }
131//! ```
132
133use crate::loom::cell::UnsafeCell;
134use crate::loom::sync::atomic::{AtomicBool, AtomicUsize};
135use crate::loom::sync::{Arc, Mutex, MutexGuard};
136use crate::task::coop::cooperative;
137use crate::util::linked_list::{self, GuardedLinkedList, LinkedList};
138use crate::util::WakeList;
139
140use std::fmt;
141use std::future::Future;
142use std::marker::PhantomPinned;
143use std::pin::Pin;
144use std::ptr::NonNull;
145use std::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release};
146use std::task::{ready, Context, Poll, Waker};
147
148/// Sending-half of the [`broadcast`] channel.
149///
150/// May be used from many threads. Messages can be sent with
151/// [`send`][Sender::send].
152///
153/// # Examples
154///
155/// ```
156/// use tokio::sync::broadcast;
157///
158/// # #[tokio::main(flavor = "current_thread")]
159/// # async fn main() {
160/// let (tx, mut rx1) = broadcast::channel(16);
161/// let mut rx2 = tx.subscribe();
162///
163/// tokio::spawn(async move {
164/// assert_eq!(rx1.recv().await.unwrap(), 10);
165/// assert_eq!(rx1.recv().await.unwrap(), 20);
166/// });
167///
168/// tokio::spawn(async move {
169/// assert_eq!(rx2.recv().await.unwrap(), 10);
170/// assert_eq!(rx2.recv().await.unwrap(), 20);
171/// });
172///
173/// tx.send(10).unwrap();
174/// tx.send(20).unwrap();
175/// # }
176/// ```
177///
178/// [`broadcast`]: crate::sync::broadcast
179pub struct Sender<T> {
180 shared: Arc<Shared<T>>,
181}
182
183/// A sender that does not prevent the channel from being closed.
184///
185/// If all [`Sender`] instances of a channel were dropped and only `WeakSender`
186/// instances remain, the channel is closed.
187///
188/// In order to send messages, the `WeakSender` needs to be upgraded using
189/// [`WeakSender::upgrade`], which returns `Option<Sender>`. It returns `None`
190/// if all `Sender`s have been dropped, and otherwise it returns a `Sender`.
191///
192/// [`Sender`]: Sender
193/// [`WeakSender::upgrade`]: WeakSender::upgrade
194///
195/// # Examples
196///
197/// ```
198/// use tokio::sync::broadcast::channel;
199///
200/// # #[tokio::main(flavor = "current_thread")]
201/// # async fn main() {
202/// let (tx, _rx) = channel::<i32>(15);
203/// let tx_weak = tx.downgrade();
204///
205/// // Upgrading will succeed because `tx` still exists.
206/// assert!(tx_weak.upgrade().is_some());
207///
208/// // If we drop `tx`, then it will fail.
209/// drop(tx);
210/// assert!(tx_weak.clone().upgrade().is_none());
211/// # }
212/// ```
213pub struct WeakSender<T> {
214 shared: Arc<Shared<T>>,
215}
216
217/// Receiving-half of the [`broadcast`] channel.
218///
219/// Must not be used concurrently. Messages may be retrieved using
220/// [`recv`][Receiver::recv].
221///
222/// To turn this receiver into a `Stream`, you can use the [`BroadcastStream`]
223/// wrapper.
224///
225/// [`BroadcastStream`]: https://docs.rs/tokio-stream/0.1/tokio_stream/wrappers/struct.BroadcastStream.html
226///
227/// # Examples
228///
229/// ```
230/// use tokio::sync::broadcast;
231///
232/// # #[tokio::main(flavor = "current_thread")]
233/// # async fn main() {
234/// let (tx, mut rx1) = broadcast::channel(16);
235/// let mut rx2 = tx.subscribe();
236///
237/// tokio::spawn(async move {
238/// assert_eq!(rx1.recv().await.unwrap(), 10);
239/// assert_eq!(rx1.recv().await.unwrap(), 20);
240/// });
241///
242/// tokio::spawn(async move {
243/// assert_eq!(rx2.recv().await.unwrap(), 10);
244/// assert_eq!(rx2.recv().await.unwrap(), 20);
245/// });
246///
247/// tx.send(10).unwrap();
248/// tx.send(20).unwrap();
249/// # }
250/// ```
251///
252/// [`broadcast`]: crate::sync::broadcast
253pub struct Receiver<T> {
254 /// State shared with all receivers and senders.
255 shared: Arc<Shared<T>>,
256
257 /// Next position to read from
258 next: u64,
259}
260
261pub mod error {
262 //! Broadcast error types
263
264 use std::fmt;
265
266 /// Error returned by the [`send`] function on a [`Sender`].
267 ///
268 /// A **send** operation can only fail if there are no active receivers,
269 /// implying that the message could never be received. The error contains the
270 /// message being sent as a payload so it can be recovered.
271 ///
272 /// [`send`]: crate::sync::broadcast::Sender::send
273 /// [`Sender`]: crate::sync::broadcast::Sender
274 #[derive(Debug)]
275 pub struct SendError<T>(pub T);
276
277 impl<T> fmt::Display for SendError<T> {
278 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
279 write!(f, "channel closed")
280 }
281 }
282
283 impl<T: fmt::Debug> std::error::Error for SendError<T> {}
284
285 /// An error returned from the [`recv`] function on a [`Receiver`].
286 ///
287 /// [`recv`]: crate::sync::broadcast::Receiver::recv
288 /// [`Receiver`]: crate::sync::broadcast::Receiver
289 #[derive(Debug, PartialEq, Eq, Clone)]
290 pub enum RecvError {
291 /// There are no more active senders implying no further messages will ever
292 /// be sent.
293 Closed,
294
295 /// The receiver lagged too far behind: one or more messages were
296 /// overwritten in the ring buffer before this receiver could read them.
297 ///
298 /// The receiver remains subscribed. Its internal cursor has been advanced
299 /// to the oldest message still retained by the channel; the next
300 /// successful [`recv`] call returns that message (unless further sends
301 /// overwrite it first).
302 ///
303 /// The `u64` is the number of messages that were skipped (dropped before
304 /// the receiver's previous cursor position).
305 ///
306 /// [`recv`]: crate::sync::broadcast::Receiver::recv
307 Lagged(u64),
308 }
309
310 impl fmt::Display for RecvError {
311 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
312 match self {
313 RecvError::Closed => write!(f, "channel closed"),
314 RecvError::Lagged(amt) => write!(f, "channel lagged by {amt}"),
315 }
316 }
317 }
318
319 impl std::error::Error for RecvError {}
320
321 /// An error returned from the [`try_recv`] function on a [`Receiver`].
322 ///
323 /// [`try_recv`]: crate::sync::broadcast::Receiver::try_recv
324 /// [`Receiver`]: crate::sync::broadcast::Receiver
325 #[derive(Debug, PartialEq, Eq, Clone)]
326 pub enum TryRecvError {
327 /// The channel is currently empty. There are still active
328 /// [`Sender`] handles, so data may yet become available.
329 ///
330 /// [`Sender`]: crate::sync::broadcast::Sender
331 Empty,
332
333 /// There are no more active senders implying no further messages will ever
334 /// be sent.
335 Closed,
336
337 /// The receiver lagged too far behind: one or more messages were
338 /// overwritten in the ring buffer before this receiver could read them.
339 ///
340 /// The receiver remains subscribed. Its internal cursor has been advanced
341 /// to the oldest message still retained by the channel; the next
342 /// successful [`try_recv`] call returns that message (unless further sends
343 /// overwrite it first).
344 ///
345 /// The `u64` is the number of messages that were skipped (dropped before
346 /// the receiver's previous cursor position).
347 ///
348 /// [`try_recv`]: crate::sync::broadcast::Receiver::try_recv
349 Lagged(u64),
350 }
351
352 impl fmt::Display for TryRecvError {
353 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354 match self {
355 TryRecvError::Empty => write!(f, "channel empty"),
356 TryRecvError::Closed => write!(f, "channel closed"),
357 TryRecvError::Lagged(amt) => write!(f, "channel lagged by {amt}"),
358 }
359 }
360 }
361
362 impl std::error::Error for TryRecvError {}
363}
364
365use self::error::{RecvError, SendError, TryRecvError};
366
367use super::Notify;
368
369/// Data shared between senders and receivers.
370struct Shared<T> {
371 /// slots in the channel.
372 buffer: Box<[Mutex<Slot<T>>]>,
373
374 /// Mask a position -> index.
375 mask: usize,
376
377 /// Tail of the queue. Includes the rx wait list.
378 tail: Mutex<Tail>,
379
380 /// Number of outstanding Sender handles.
381 num_tx: AtomicUsize,
382
383 /// Number of outstanding weak Sender handles.
384 num_weak_tx: AtomicUsize,
385
386 /// Notify when the last subscribed [`Receiver`] drops.
387 notify_last_rx_drop: Notify,
388}
389
390/// Next position to write a value.
391struct Tail {
392 /// Next position to write to.
393 pos: u64,
394
395 /// Number of active receivers.
396 rx_cnt: usize,
397
398 /// True if the channel is closed.
399 closed: bool,
400
401 /// Receivers waiting for a value.
402 waiters: LinkedList<Waiter>,
403}
404
405/// Slot in the buffer.
406struct Slot<T> {
407 /// Remaining number of receivers that are expected to see this value.
408 ///
409 /// When this goes to zero, the value is released.
410 ///
411 /// Access is protected by the slot mutex.
412 rem: usize,
413
414 /// Uniquely identifies the `send` stored in the slot.
415 pos: u64,
416
417 /// The value being broadcast.
418 ///
419 /// The value is set by `send` while the slot mutex is held. When a reader
420 /// drops, `rem` is decremented. When it hits zero, the value is dropped.
421 val: Option<T>,
422}
423
424/// An entry in the wait queue.
425struct Waiter {
426 /// True if queued.
427 queued: AtomicBool,
428
429 /// Task waiting on the broadcast channel.
430 waker: Option<Waker>,
431
432 /// Intrusive linked-list pointers.
433 pointers: linked_list::Pointers<Waiter>,
434
435 /// Should not be `Unpin`.
436 _p: PhantomPinned,
437}
438
439impl Waiter {
440 fn new() -> Self {
441 Self {
442 queued: AtomicBool::new(false),
443 waker: None,
444 pointers: linked_list::Pointers::new(),
445 _p: PhantomPinned,
446 }
447 }
448}
449
450generate_addr_of_methods! {
451 impl<> Waiter {
452 unsafe fn addr_of_pointers(self: NonNull<Self>) -> NonNull<linked_list::Pointers<Waiter>> {
453 &self.pointers
454 }
455 }
456}
457
458struct RecvGuard<'a, T> {
459 slot: MutexGuard<'a, Slot<T>>,
460}
461
462/// Receive a value future.
463struct Recv<'a, T> {
464 /// Receiver being waited on.
465 receiver: &'a mut Receiver<T>,
466
467 /// Entry in the waiter `LinkedList`.
468 waiter: WaiterCell,
469}
470
471// The wrapper around `UnsafeCell` isolates the unsafe impl `Send` and `Sync`
472// from `Recv`.
473struct WaiterCell(UnsafeCell<Waiter>);
474
475unsafe impl Send for WaiterCell {}
476unsafe impl Sync for WaiterCell {}
477
478/// Max number of receivers. Reserve space to lock.
479const MAX_RECEIVERS: usize = usize::MAX >> 2;
480
481/// Create a bounded, multi-producer, multi-consumer channel where each sent
482/// value is broadcasted to all active receivers.
483///
484/// **Note:** The provided `capacity` is rounded **up** to the next power of
485/// two. That rounded size is the number of messages the internal ring buffer
486/// can retain, and is what [lag detection](self#lagging) uses. For example,
487/// `channel(3)` behaves as if the capacity were 4.
488///
489/// All data sent on [`Sender`] will become available on every active
490/// [`Receiver`] in the same order as it was sent.
491///
492/// The `Sender` can be cloned to `send` to the same channel from multiple
493/// points in the process or it can be used concurrently from an `Arc`. New
494/// `Receiver` handles are created by calling [`Sender::subscribe`].
495///
496/// If all [`Receiver`] handles are dropped, the `send` method will return a
497/// [`SendError`]. Similarly, if all [`Sender`] handles are dropped, the [`recv`]
498/// method will return a [`RecvError`].
499///
500/// [`Sender`]: crate::sync::broadcast::Sender
501/// [`Sender::subscribe`]: crate::sync::broadcast::Sender::subscribe
502/// [`Receiver`]: crate::sync::broadcast::Receiver
503/// [`recv`]: crate::sync::broadcast::Receiver::recv
504/// [`SendError`]: crate::sync::broadcast::error::SendError
505/// [`RecvError`]: crate::sync::broadcast::error::RecvError
506///
507/// # Examples
508///
509/// ```
510/// use tokio::sync::broadcast;
511///
512/// # #[tokio::main(flavor = "current_thread")]
513/// # async fn main() {
514/// let (tx, mut rx1) = broadcast::channel(16);
515/// let mut rx2 = tx.subscribe();
516///
517/// tokio::spawn(async move {
518/// assert_eq!(rx1.recv().await.unwrap(), 10);
519/// assert_eq!(rx1.recv().await.unwrap(), 20);
520/// });
521///
522/// tokio::spawn(async move {
523/// assert_eq!(rx2.recv().await.unwrap(), 10);
524/// assert_eq!(rx2.recv().await.unwrap(), 20);
525/// });
526///
527/// tx.send(10).unwrap();
528/// tx.send(20).unwrap();
529/// # }
530/// ```
531///
532/// # Panics
533///
534/// This will panic if `capacity` is equal to `0` or exceeds `usize::MAX / 2`.
535///
536/// This pre-allocates space for `capacity` messages. Allocation failure may result in a panic or
537/// [an allocation error](std::alloc::handle_alloc_error).
538#[track_caller]
539pub fn channel<T: Clone>(capacity: usize) -> (Sender<T>, Receiver<T>) {
540 // SAFETY: In the line below we are creating one extra receiver, so there will be 1 in total.
541 let tx = unsafe { Sender::new_with_receiver_count(1, capacity) };
542 let rx = Receiver {
543 shared: tx.shared.clone(),
544 next: 0,
545 };
546 (tx, rx)
547}
548
549impl<T> Sender<T> {
550 /// Creates the sending-half of the [`broadcast`] channel.
551 ///
552 /// See the documentation of [`broadcast::channel`] for more information on this method.
553 ///
554 /// [`broadcast`]: crate::sync::broadcast
555 /// [`broadcast::channel`]: crate::sync::broadcast::channel
556 #[track_caller]
557 pub fn new(capacity: usize) -> Self {
558 // SAFETY: We don't create extra receivers, so there are 0.
559 unsafe { Self::new_with_receiver_count(0, capacity) }
560 }
561
562 /// Creates the sending-half of the [`broadcast`](self) channel, and provide the receiver
563 /// count.
564 ///
565 /// See the documentation of [`broadcast::channel`](self::channel) for more errors when
566 /// calling this function.
567 ///
568 /// # Safety:
569 ///
570 /// The caller must ensure that the amount of receivers for this Sender is correct before
571 /// the channel functionalities are used, the count is zero by default, as this function
572 /// does not create any receivers by itself.
573 #[track_caller]
574 unsafe fn new_with_receiver_count(receiver_count: usize, mut capacity: usize) -> Self {
575 assert!(capacity > 0, "broadcast channel capacity cannot be zero");
576 assert!(
577 capacity <= usize::MAX >> 1,
578 "broadcast channel capacity exceeded `usize::MAX / 2`"
579 );
580
581 // Round to a power of two
582 capacity = capacity.next_power_of_two();
583
584 let buffer = (0..capacity).map(|i| {
585 Mutex::new(Slot {
586 rem: 0,
587 pos: (i as u64).wrapping_sub(capacity as u64),
588 val: None,
589 })
590 });
591
592 let shared = Arc::new(Shared {
593 buffer: buffer.collect(),
594 mask: capacity - 1,
595 tail: Mutex::new(Tail {
596 pos: 0,
597 rx_cnt: receiver_count,
598 closed: receiver_count == 0,
599 waiters: LinkedList::new(),
600 }),
601 num_tx: AtomicUsize::new(1),
602 num_weak_tx: AtomicUsize::new(0),
603 notify_last_rx_drop: Notify::new(),
604 });
605
606 Sender { shared }
607 }
608
609 /// Attempts to send a value to all active [`Receiver`] handles, returning
610 /// it back if it could not be sent.
611 ///
612 /// A successful send occurs when there is at least one active [`Receiver`]
613 /// handle. An unsuccessful send would be one where all associated
614 /// [`Receiver`] handles have already been dropped.
615 ///
616 /// # Return
617 ///
618 /// On success, the number of subscribed [`Receiver`] handles is returned.
619 /// This does not mean that this number of receivers will see the message as
620 /// a receiver may drop or lag ([see lagging](self#lagging)) before receiving
621 /// the message.
622 ///
623 /// # Note
624 ///
625 /// A return value of `Ok` **does not** mean that the sent value will be
626 /// observed by all or any of the active [`Receiver`] handles. [`Receiver`]
627 /// handles may be dropped before receiving the sent message.
628 ///
629 /// A return value of `Err` **does not** mean that future calls to `send`
630 /// will fail. New [`Receiver`] handles may be created by calling
631 /// [`subscribe`].
632 ///
633 /// [`Receiver`]: crate::sync::broadcast::Receiver
634 /// [`subscribe`]: crate::sync::broadcast::Sender::subscribe
635 ///
636 /// # Examples
637 ///
638 /// ```
639 /// use tokio::sync::broadcast;
640 ///
641 /// # #[tokio::main(flavor = "current_thread")]
642 /// # async fn main() {
643 /// let (tx, mut rx1) = broadcast::channel(16);
644 /// let mut rx2 = tx.subscribe();
645 ///
646 /// tokio::spawn(async move {
647 /// assert_eq!(rx1.recv().await.unwrap(), 10);
648 /// assert_eq!(rx1.recv().await.unwrap(), 20);
649 /// });
650 ///
651 /// tokio::spawn(async move {
652 /// assert_eq!(rx2.recv().await.unwrap(), 10);
653 /// assert_eq!(rx2.recv().await.unwrap(), 20);
654 /// });
655 ///
656 /// tx.send(10).unwrap();
657 /// tx.send(20).unwrap();
658 /// # }
659 /// ```
660 pub fn send(&self, value: T) -> Result<usize, SendError<T>> {
661 let mut tail = self.shared.tail.lock();
662
663 if tail.rx_cnt == 0 {
664 return Err(SendError(value));
665 }
666
667 // Position to write into
668 let pos = tail.pos;
669 let rem = tail.rx_cnt;
670 let idx = (pos & self.shared.mask as u64) as usize;
671
672 // Update the tail position
673 tail.pos = tail.pos.wrapping_add(1);
674
675 // Get the slot
676 let mut slot = self.shared.buffer[idx].lock();
677
678 // Track the position
679 slot.pos = pos;
680
681 // Set remaining receivers
682 slot.rem = rem;
683
684 // Write the value
685 slot.val = Some(value);
686
687 // Release the slot lock before notifying the receivers.
688 drop(slot);
689
690 // Notify and release the mutex. This must happen after the slot lock is
691 // released, otherwise the writer lock bit could be cleared while another
692 // thread is in the critical section.
693 self.shared.notify_rx(tail);
694
695 Ok(rem)
696 }
697
698 /// Creates a new [`Receiver`] handle that will receive values sent **after**
699 /// this call to `subscribe`.
700 ///
701 /// # Examples
702 ///
703 /// ```
704 /// use tokio::sync::broadcast;
705 ///
706 /// # #[tokio::main(flavor = "current_thread")]
707 /// # async fn main() {
708 /// let (tx, _rx) = broadcast::channel(16);
709 ///
710 /// // Will not be seen
711 /// tx.send(10).unwrap();
712 ///
713 /// let mut rx = tx.subscribe();
714 ///
715 /// tx.send(20).unwrap();
716 ///
717 /// let value = rx.recv().await.unwrap();
718 /// assert_eq!(20, value);
719 /// # }
720 /// ```
721 pub fn subscribe(&self) -> Receiver<T> {
722 let shared = self.shared.clone();
723 new_receiver(shared)
724 }
725
726 /// Converts the `Sender` to a [`WeakSender`] that does not count
727 /// towards RAII semantics, i.e. if all `Sender` instances of the
728 /// channel were dropped and only `WeakSender` instances remain,
729 /// the channel is closed.
730 #[must_use = "Downgrade creates a WeakSender without destroying the original non-weak sender."]
731 pub fn downgrade(&self) -> WeakSender<T> {
732 self.shared.num_weak_tx.fetch_add(1, Relaxed);
733 WeakSender {
734 shared: self.shared.clone(),
735 }
736 }
737
738 /// Returns the number of queued values.
739 ///
740 /// A value is queued until it has either been seen by all receivers that were alive at the time
741 /// it was sent, or has been evicted from the queue by subsequent sends that exceeded the
742 /// queue's capacity.
743 ///
744 /// # Note
745 ///
746 /// In contrast to [`Receiver::len`], this method only reports queued values and not values that
747 /// have been evicted from the queue before being seen by all receivers.
748 ///
749 /// # Examples
750 ///
751 /// ```
752 /// use tokio::sync::broadcast;
753 ///
754 /// # #[tokio::main(flavor = "current_thread")]
755 /// # async fn main() {
756 /// let (tx, mut rx1) = broadcast::channel(16);
757 /// let mut rx2 = tx.subscribe();
758 ///
759 /// tx.send(10).unwrap();
760 /// tx.send(20).unwrap();
761 /// tx.send(30).unwrap();
762 ///
763 /// assert_eq!(tx.len(), 3);
764 ///
765 /// rx1.recv().await.unwrap();
766 ///
767 /// // The len is still 3 since rx2 hasn't seen the first value yet.
768 /// assert_eq!(tx.len(), 3);
769 ///
770 /// rx2.recv().await.unwrap();
771 ///
772 /// assert_eq!(tx.len(), 2);
773 /// # }
774 /// ```
775 pub fn len(&self) -> usize {
776 let tail = self.shared.tail.lock();
777
778 let base_idx = (tail.pos & self.shared.mask as u64) as usize;
779 let mut low = 0;
780 let mut high = self.shared.buffer.len();
781 while low < high {
782 let mid = low + (high - low) / 2;
783 let idx = base_idx.wrapping_add(mid) & self.shared.mask;
784 if self.shared.buffer[idx].lock().rem == 0 {
785 low = mid + 1;
786 } else {
787 high = mid;
788 }
789 }
790
791 self.shared.buffer.len() - low
792 }
793
794 /// Returns true if there are no queued values.
795 ///
796 /// # Examples
797 ///
798 /// ```
799 /// use tokio::sync::broadcast;
800 ///
801 /// # #[tokio::main(flavor = "current_thread")]
802 /// # async fn main() {
803 /// let (tx, mut rx1) = broadcast::channel(16);
804 /// let mut rx2 = tx.subscribe();
805 ///
806 /// assert!(tx.is_empty());
807 ///
808 /// tx.send(10).unwrap();
809 ///
810 /// assert!(!tx.is_empty());
811 ///
812 /// rx1.recv().await.unwrap();
813 ///
814 /// // The queue is still not empty since rx2 hasn't seen the value.
815 /// assert!(!tx.is_empty());
816 ///
817 /// rx2.recv().await.unwrap();
818 ///
819 /// assert!(tx.is_empty());
820 /// # }
821 /// ```
822 pub fn is_empty(&self) -> bool {
823 let tail = self.shared.tail.lock();
824
825 let idx = (tail.pos.wrapping_sub(1) & self.shared.mask as u64) as usize;
826 self.shared.buffer[idx].lock().rem == 0
827 }
828
829 /// Returns the number of active receivers.
830 ///
831 /// An active receiver is a [`Receiver`] handle returned from [`channel`] or
832 /// [`subscribe`]. These are the handles that will receive values sent on
833 /// this [`Sender`].
834 ///
835 /// # Note
836 ///
837 /// It is not guaranteed that a sent message will reach this number of
838 /// receivers. Active receivers may never call [`recv`] again before
839 /// dropping.
840 ///
841 /// [`recv`]: crate::sync::broadcast::Receiver::recv
842 /// [`Receiver`]: crate::sync::broadcast::Receiver
843 /// [`Sender`]: crate::sync::broadcast::Sender
844 /// [`subscribe`]: crate::sync::broadcast::Sender::subscribe
845 /// [`channel`]: crate::sync::broadcast::channel
846 ///
847 /// # Examples
848 ///
849 /// ```
850 /// use tokio::sync::broadcast;
851 ///
852 /// # #[tokio::main(flavor = "current_thread")]
853 /// # async fn main() {
854 /// let (tx, _rx1) = broadcast::channel(16);
855 ///
856 /// assert_eq!(1, tx.receiver_count());
857 ///
858 /// let mut _rx2 = tx.subscribe();
859 ///
860 /// assert_eq!(2, tx.receiver_count());
861 ///
862 /// tx.send(10).unwrap();
863 /// # }
864 /// ```
865 pub fn receiver_count(&self) -> usize {
866 let tail = self.shared.tail.lock();
867 tail.rx_cnt
868 }
869
870 /// Returns `true` if senders belong to the same channel.
871 ///
872 /// # Examples
873 ///
874 /// ```
875 /// use tokio::sync::broadcast;
876 ///
877 /// # #[tokio::main(flavor = "current_thread")]
878 /// # async fn main() {
879 /// let (tx, _rx) = broadcast::channel::<()>(16);
880 /// let tx2 = tx.clone();
881 ///
882 /// assert!(tx.same_channel(&tx2));
883 ///
884 /// let (tx3, _rx3) = broadcast::channel::<()>(16);
885 ///
886 /// assert!(!tx3.same_channel(&tx2));
887 /// # }
888 /// ```
889 pub fn same_channel(&self, other: &Self) -> bool {
890 Arc::ptr_eq(&self.shared, &other.shared)
891 }
892
893 /// A future which completes when the number of [Receiver]s subscribed to this `Sender` reaches
894 /// zero.
895 ///
896 /// # Examples
897 ///
898 /// ```
899 /// use futures::FutureExt;
900 /// use tokio::sync::broadcast;
901 ///
902 /// # #[tokio::main(flavor = "current_thread")]
903 /// # async fn main() {
904 /// let (tx, mut rx1) = broadcast::channel::<u32>(16);
905 /// let mut rx2 = tx.subscribe();
906 ///
907 /// let _ = tx.send(10);
908 ///
909 /// assert_eq!(rx1.recv().await.unwrap(), 10);
910 /// drop(rx1);
911 /// assert!(tx.closed().now_or_never().is_none());
912 ///
913 /// assert_eq!(rx2.recv().await.unwrap(), 10);
914 /// drop(rx2);
915 /// assert!(tx.closed().now_or_never().is_some());
916 /// # }
917 /// ```
918 pub async fn closed(&self) {
919 loop {
920 let notified = self.shared.notify_last_rx_drop.notified();
921
922 {
923 // Ensure the lock drops if the channel isn't closed
924 let tail = self.shared.tail.lock();
925 if tail.closed {
926 return;
927 }
928 }
929
930 notified.await;
931 }
932 }
933
934 fn close_channel(&self) {
935 let mut tail = self.shared.tail.lock();
936 tail.closed = true;
937
938 self.shared.notify_rx(tail);
939 }
940
941 /// Returns the number of [`Sender`] handles.
942 pub fn strong_count(&self) -> usize {
943 self.shared.num_tx.load(Acquire)
944 }
945
946 /// Returns the number of [`WeakSender`] handles.
947 pub fn weak_count(&self) -> usize {
948 self.shared.num_weak_tx.load(Acquire)
949 }
950}
951
952/// Create a new `Receiver` which reads starting from the tail.
953fn new_receiver<T>(shared: Arc<Shared<T>>) -> Receiver<T> {
954 let mut tail = shared.tail.lock();
955
956 assert!(tail.rx_cnt != MAX_RECEIVERS, "max receivers");
957
958 if tail.rx_cnt == 0 {
959 // Potentially need to re-open the channel, if a new receiver has been added between calls
960 // to poll(). Note that we use rx_cnt == 0 instead of is_closed since is_closed also
961 // applies if the sender has been dropped
962 tail.closed = false;
963 }
964
965 tail.rx_cnt = tail.rx_cnt.checked_add(1).expect("overflow");
966 let next = tail.pos;
967
968 drop(tail);
969
970 Receiver { shared, next }
971}
972
973/// List used in `Shared::notify_rx`. It wraps a guarded linked list
974/// and gates the access to it on the `Shared.tail` mutex. It also empties
975/// the list on drop.
976struct WaitersList<'a, T> {
977 list: GuardedLinkedList<Waiter>,
978 is_empty: bool,
979 shared: &'a Shared<T>,
980}
981
982impl<'a, T> Drop for WaitersList<'a, T> {
983 fn drop(&mut self) {
984 // If the list is not empty, we unlink all waiters from it.
985 // We do not wake the waiters to avoid double panics.
986 if !self.is_empty {
987 let _lock_guard = self.shared.tail.lock();
988 while self.list.pop_back().is_some() {}
989 }
990 }
991}
992
993impl<'a, T> WaitersList<'a, T> {
994 fn new(
995 unguarded_list: LinkedList<Waiter>,
996 guard: Pin<&'a Waiter>,
997 shared: &'a Shared<T>,
998 ) -> Self {
999 let guard_ptr = NonNull::from(guard.get_ref());
1000 let list = unguarded_list.into_guarded(guard_ptr);
1001 WaitersList {
1002 list,
1003 is_empty: false,
1004 shared,
1005 }
1006 }
1007
1008 /// Removes the last element from the guarded list. Modifying this list
1009 /// requires an exclusive access to the main list in `Notify`.
1010 fn pop_back_locked(&mut self, _tail: &mut Tail) -> Option<NonNull<Waiter>> {
1011 let result = self.list.pop_back();
1012 if result.is_none() {
1013 // Save information about emptiness to avoid waiting for lock
1014 // in the destructor.
1015 self.is_empty = true;
1016 }
1017 result
1018 }
1019}
1020
1021impl<T> Shared<T> {
1022 fn notify_rx<'a, 'b: 'a>(&'b self, mut tail: MutexGuard<'a, Tail>) {
1023 // It is critical for `GuardedLinkedList` safety that the guard node is
1024 // pinned in memory and is not dropped until the guarded list is dropped.
1025 let guard = Waiter::new();
1026 pin!(guard);
1027
1028 // We move all waiters to a secondary list. It uses a `GuardedLinkedList`
1029 // underneath to allow every waiter to safely remove itself from it.
1030 //
1031 // * This list will be still guarded by the `waiters` lock.
1032 // `NotifyWaitersList` wrapper makes sure we hold the lock to modify it.
1033 // * This wrapper will empty the list on drop. It is critical for safety
1034 // that we will not leave any list entry with a pointer to the local
1035 // guard node after this function returns / panics.
1036 let mut list = WaitersList::new(std::mem::take(&mut tail.waiters), guard.as_ref(), self);
1037
1038 let mut wakers = WakeList::new();
1039 'outer: loop {
1040 while wakers.can_push() {
1041 match list.pop_back_locked(&mut tail) {
1042 Some(waiter) => {
1043 unsafe {
1044 // Safety: accessing `waker` is safe because
1045 // the tail lock is held.
1046 if let Some(waker) = (*waiter.as_ptr()).waker.take() {
1047 wakers.push(waker);
1048 }
1049
1050 // Safety: `queued` is atomic.
1051 let queued = &(*waiter.as_ptr()).queued;
1052 // `Relaxed` suffices because the tail lock is held.
1053 assert!(queued.load(Relaxed));
1054 // `Release` is needed to synchronize with `Recv::drop`.
1055 // It is critical to set this variable **after** waker
1056 // is extracted, otherwise we may data race with `Recv::drop`.
1057 queued.store(false, Release);
1058 }
1059 }
1060 None => {
1061 break 'outer;
1062 }
1063 }
1064 }
1065
1066 // Release the lock before waking.
1067 drop(tail);
1068
1069 // Before we acquire the lock again all sorts of things can happen:
1070 // some waiters may remove themselves from the list and new waiters
1071 // may be added. This is fine since at worst we will unnecessarily
1072 // wake up waiters which will then queue themselves again.
1073
1074 wakers.wake_all();
1075
1076 // Acquire the lock again.
1077 tail = self.tail.lock();
1078 }
1079
1080 // Release the lock before waking.
1081 drop(tail);
1082
1083 wakers.wake_all();
1084 }
1085}
1086
1087impl<T> Clone for Sender<T> {
1088 fn clone(&self) -> Sender<T> {
1089 let shared = self.shared.clone();
1090 shared.num_tx.fetch_add(1, Relaxed);
1091
1092 Sender { shared }
1093 }
1094}
1095
1096impl<T> Drop for Sender<T> {
1097 fn drop(&mut self) {
1098 if 1 == self.shared.num_tx.fetch_sub(1, AcqRel) {
1099 self.close_channel();
1100 }
1101 }
1102}
1103
1104impl<T> WeakSender<T> {
1105 /// Tries to convert a `WeakSender` into a [`Sender`].
1106 ///
1107 /// This will return `Some` if there are other `Sender` instances alive and
1108 /// the channel wasn't previously dropped, otherwise `None` is returned.
1109 #[must_use]
1110 pub fn upgrade(&self) -> Option<Sender<T>> {
1111 let mut tx_count = self.shared.num_tx.load(Acquire);
1112
1113 loop {
1114 if tx_count == 0 {
1115 // channel is closed so this WeakSender can not be upgraded
1116 return None;
1117 }
1118
1119 match self
1120 .shared
1121 .num_tx
1122 .compare_exchange_weak(tx_count, tx_count + 1, Relaxed, Acquire)
1123 {
1124 Ok(_) => {
1125 return Some(Sender {
1126 shared: self.shared.clone(),
1127 })
1128 }
1129 Err(prev_count) => tx_count = prev_count,
1130 }
1131 }
1132 }
1133
1134 /// Returns the number of [`Sender`] handles.
1135 pub fn strong_count(&self) -> usize {
1136 self.shared.num_tx.load(Acquire)
1137 }
1138
1139 /// Returns the number of [`WeakSender`] handles.
1140 pub fn weak_count(&self) -> usize {
1141 self.shared.num_weak_tx.load(Acquire)
1142 }
1143}
1144
1145impl<T> Clone for WeakSender<T> {
1146 fn clone(&self) -> WeakSender<T> {
1147 let shared = self.shared.clone();
1148 shared.num_weak_tx.fetch_add(1, Relaxed);
1149
1150 Self { shared }
1151 }
1152}
1153
1154impl<T> Drop for WeakSender<T> {
1155 fn drop(&mut self) {
1156 self.shared.num_weak_tx.fetch_sub(1, AcqRel);
1157 }
1158}
1159
1160impl<T> Receiver<T> {
1161 /// Returns the number of messages that were sent into the channel and that
1162 /// this [`Receiver`] has yet to receive.
1163 ///
1164 /// This count includes messages that have already been overwritten in the
1165 /// ring buffer and are no longer readable. If `len` is **greater than** the
1166 /// channel's effective capacity (the provided capacity rounded up to the
1167 /// next power of two), the next call to [`recv`] returns
1168 /// `Err(RecvError::Lagged)` and the next call to [`try_recv`] returns
1169 /// `Err(TryRecvError::Lagged)`. For example, with `channel(10)` the buffer
1170 /// length is 16, so lagging begins once `len` is larger than 16.
1171 ///
1172 /// After a successful receive (including after handling `Lagged` and then
1173 /// reading retained messages), `len` decreases accordingly.
1174 ///
1175 /// [`Receiver`]: crate::sync::broadcast::Receiver
1176 /// [`recv`]: crate::sync::broadcast::Receiver::recv
1177 /// [`try_recv`]: crate::sync::broadcast::Receiver::try_recv
1178 ///
1179 /// # Examples
1180 ///
1181 /// ```
1182 /// use tokio::sync::broadcast;
1183 ///
1184 /// # #[tokio::main(flavor = "current_thread")]
1185 /// # async fn main() {
1186 /// let (tx, mut rx1) = broadcast::channel(16);
1187 ///
1188 /// tx.send(10).unwrap();
1189 /// tx.send(20).unwrap();
1190 ///
1191 /// assert_eq!(rx1.len(), 2);
1192 /// assert_eq!(rx1.recv().await.unwrap(), 10);
1193 /// assert_eq!(rx1.len(), 1);
1194 /// assert_eq!(rx1.recv().await.unwrap(), 20);
1195 /// assert_eq!(rx1.len(), 0);
1196 /// # }
1197 /// ```
1198 pub fn len(&self) -> usize {
1199 let next_send_pos = self.shared.tail.lock().pos;
1200 (next_send_pos - self.next) as usize
1201 }
1202
1203 /// Returns true if there aren't any messages in the channel that the [`Receiver`]
1204 /// has yet to receive.
1205 ///
1206 /// [`Receiver`]: crate::sync::broadcast::Receiver
1207 ///
1208 /// # Examples
1209 ///
1210 /// ```
1211 /// use tokio::sync::broadcast;
1212 ///
1213 /// # #[tokio::main(flavor = "current_thread")]
1214 /// # async fn main() {
1215 /// let (tx, mut rx1) = broadcast::channel(16);
1216 ///
1217 /// assert!(rx1.is_empty());
1218 ///
1219 /// tx.send(10).unwrap();
1220 /// tx.send(20).unwrap();
1221 ///
1222 /// assert!(!rx1.is_empty());
1223 /// assert_eq!(rx1.recv().await.unwrap(), 10);
1224 /// assert_eq!(rx1.recv().await.unwrap(), 20);
1225 /// assert!(rx1.is_empty());
1226 /// # }
1227 /// ```
1228 pub fn is_empty(&self) -> bool {
1229 self.len() == 0
1230 }
1231
1232 /// Returns `true` if receivers belong to the same channel.
1233 ///
1234 /// # Examples
1235 ///
1236 /// ```
1237 /// use tokio::sync::broadcast;
1238 ///
1239 /// # #[tokio::main(flavor = "current_thread")]
1240 /// # async fn main() {
1241 /// let (tx, rx) = broadcast::channel::<()>(16);
1242 /// let rx2 = tx.subscribe();
1243 ///
1244 /// assert!(rx.same_channel(&rx2));
1245 ///
1246 /// let (_tx3, rx3) = broadcast::channel::<()>(16);
1247 ///
1248 /// assert!(!rx3.same_channel(&rx2));
1249 /// # }
1250 /// ```
1251 pub fn same_channel(&self, other: &Self) -> bool {
1252 Arc::ptr_eq(&self.shared, &other.shared)
1253 }
1254
1255 /// Locks the next value if there is one.
1256 fn recv_ref(
1257 &mut self,
1258 waiter: Option<(&UnsafeCell<Waiter>, &Waker)>,
1259 ) -> Result<RecvGuard<'_, T>, TryRecvError> {
1260 let idx = (self.next & self.shared.mask as u64) as usize;
1261
1262 // The slot holding the next value to read
1263 let mut slot = self.shared.buffer[idx].lock();
1264
1265 if slot.pos != self.next {
1266 // Release the `slot` lock before attempting to acquire the `tail`
1267 // lock. This is required because `send2` acquires the tail lock
1268 // first followed by the slot lock. Acquiring the locks in reverse
1269 // order here would result in a potential deadlock: `recv_ref`
1270 // acquires the `slot` lock and attempts to acquire the `tail` lock
1271 // while `send2` acquired the `tail` lock and attempts to acquire
1272 // the slot lock.
1273 drop(slot);
1274
1275 let mut old_waker = None;
1276
1277 let mut tail = self.shared.tail.lock();
1278
1279 // Acquire slot lock again
1280 slot = self.shared.buffer[idx].lock();
1281
1282 // Make sure the position did not change. This could happen in the
1283 // unlikely event that the buffer is wrapped between dropping the
1284 // read lock and acquiring the tail lock.
1285 if slot.pos != self.next {
1286 let next_pos = slot.pos.wrapping_add(self.shared.buffer.len() as u64);
1287
1288 if next_pos == self.next {
1289 // At this point the channel is empty for *this* receiver. If
1290 // it's been closed, then that's what we return, otherwise we
1291 // set a waker and return empty.
1292 if tail.closed {
1293 return Err(TryRecvError::Closed);
1294 }
1295
1296 // Store the waker
1297 if let Some((waiter, waker)) = waiter {
1298 // Safety: called while locked.
1299 unsafe {
1300 // Only queue if not already queued
1301 waiter.with_mut(|ptr| {
1302 // If there is no waker **or** if the currently
1303 // stored waker references a **different** task,
1304 // track the tasks' waker to be notified on
1305 // receipt of a new value.
1306 match (*ptr).waker {
1307 Some(ref w) if w.will_wake(waker) => {}
1308 _ => {
1309 old_waker = (*ptr).waker.replace(waker.clone());
1310 }
1311 }
1312
1313 // If the waiter is not already queued, enqueue it.
1314 // `Relaxed` order suffices: we have synchronized with
1315 // all writers through the tail lock that we hold.
1316 if !(*ptr).queued.load(Relaxed) {
1317 // `Relaxed` order suffices: all the readers will
1318 // synchronize with this write through the tail lock.
1319 (*ptr).queued.store(true, Relaxed);
1320 tail.waiters.push_front(NonNull::new_unchecked(&mut *ptr));
1321 }
1322 });
1323 }
1324 }
1325
1326 // Drop the old waker after releasing the locks.
1327 drop(slot);
1328 drop(tail);
1329 drop(old_waker);
1330
1331 return Err(TryRecvError::Empty);
1332 }
1333
1334 // At this point, the receiver has lagged behind the sender by
1335 // more than the channel capacity. The receiver will attempt to
1336 // catch up by skipping dropped messages and setting the
1337 // internal cursor to the **oldest** message stored by the
1338 // channel.
1339 let next = tail.pos.wrapping_sub(self.shared.buffer.len() as u64);
1340
1341 let missed = next.wrapping_sub(self.next);
1342
1343 drop(tail);
1344
1345 // The receiver is slow but no values have been missed
1346 if missed == 0 {
1347 self.next = self.next.wrapping_add(1);
1348
1349 return Ok(RecvGuard { slot });
1350 }
1351
1352 self.next = next;
1353
1354 return Err(TryRecvError::Lagged(missed));
1355 }
1356 }
1357
1358 self.next = self.next.wrapping_add(1);
1359
1360 Ok(RecvGuard { slot })
1361 }
1362
1363 /// Returns the number of [`Sender`] handles.
1364 pub fn sender_strong_count(&self) -> usize {
1365 self.shared.num_tx.load(Acquire)
1366 }
1367
1368 /// Returns the number of [`WeakSender`] handles.
1369 pub fn sender_weak_count(&self) -> usize {
1370 self.shared.num_weak_tx.load(Acquire)
1371 }
1372
1373 /// Checks if a channel is closed.
1374 ///
1375 /// This method returns `true` if the channel has been closed. The channel is closed
1376 /// when all [`Sender`] have been dropped.
1377 ///
1378 /// [`Sender`]: crate::sync::broadcast::Sender
1379 ///
1380 /// # Examples
1381 /// ```
1382 /// use tokio::sync::broadcast;
1383 ///
1384 /// # #[tokio::main(flavor = "current_thread")]
1385 /// # async fn main() {
1386 /// let (tx, rx) = broadcast::channel::<()>(10);
1387 /// assert!(!rx.is_closed());
1388 ///
1389 /// drop(tx);
1390 ///
1391 /// assert!(rx.is_closed());
1392 /// # }
1393 /// ```
1394 pub fn is_closed(&self) -> bool {
1395 // Channel is closed when there are no strong senders left active
1396 self.shared.num_tx.load(Acquire) == 0
1397 }
1398}
1399
1400impl<T: Clone> Receiver<T> {
1401 /// Re-subscribes to the channel starting from the current tail element.
1402 ///
1403 /// This [`Receiver`] handle will receive a clone of all values sent
1404 /// **after** it has resubscribed. This will not include elements that are
1405 /// in the queue of the current receiver. Consider the following example.
1406 ///
1407 /// # Examples
1408 ///
1409 /// ```
1410 /// use tokio::sync::broadcast;
1411 ///
1412 /// # #[tokio::main(flavor = "current_thread")]
1413 /// # async fn main() {
1414 /// let (tx, mut rx) = broadcast::channel(2);
1415 ///
1416 /// tx.send(1).unwrap();
1417 /// let mut rx2 = rx.resubscribe();
1418 /// tx.send(2).unwrap();
1419 ///
1420 /// assert_eq!(rx2.recv().await.unwrap(), 2);
1421 /// assert_eq!(rx.recv().await.unwrap(), 1);
1422 /// # }
1423 /// ```
1424 pub fn resubscribe(&self) -> Self {
1425 let shared = self.shared.clone();
1426 new_receiver(shared)
1427 }
1428 /// Receives the next value for this receiver.
1429 ///
1430 /// Each [`Receiver`] handle will receive a clone of all values sent
1431 /// **after** it has subscribed.
1432 ///
1433 /// `Err(RecvError::Closed)` is returned when all `Sender` halves have
1434 /// dropped, indicating that no further values can be sent on the channel.
1435 ///
1436 /// If the [`Receiver`] handle falls behind, once the channel is full, newly
1437 /// sent values overwrite old values in the ring buffer. The next call to
1438 /// [`recv`] then returns `Err(RecvError::Lagged(n))`, where `n` is the
1439 /// number of overwritten messages the receiver missed. The receiver stays
1440 /// subscribed; its internal cursor is advanced to the oldest value still
1441 /// held by the channel. A subsequent call to [`recv`] returns that value,
1442 /// unless further sends overwrite it before the receiver reads it. See
1443 /// [lagging](self#lagging) for details.
1444 ///
1445 /// # Cancel safety
1446 ///
1447 /// This method is cancel safe. If `recv` is used as a branch in
1448 /// [`tokio::select!`](crate::select) and another branch
1449 /// completes first, it is guaranteed that no messages were received on this
1450 /// channel.
1451 ///
1452 /// [`Receiver`]: crate::sync::broadcast::Receiver
1453 /// [`recv`]: crate::sync::broadcast::Receiver::recv
1454 ///
1455 /// # Examples
1456 ///
1457 /// ```
1458 /// use tokio::sync::broadcast;
1459 ///
1460 /// # #[tokio::main(flavor = "current_thread")]
1461 /// # async fn main() {
1462 /// let (tx, mut rx1) = broadcast::channel(16);
1463 /// let mut rx2 = tx.subscribe();
1464 ///
1465 /// tokio::spawn(async move {
1466 /// assert_eq!(rx1.recv().await.unwrap(), 10);
1467 /// assert_eq!(rx1.recv().await.unwrap(), 20);
1468 /// });
1469 ///
1470 /// tokio::spawn(async move {
1471 /// assert_eq!(rx2.recv().await.unwrap(), 10);
1472 /// assert_eq!(rx2.recv().await.unwrap(), 20);
1473 /// });
1474 ///
1475 /// tx.send(10).unwrap();
1476 /// tx.send(20).unwrap();
1477 /// # }
1478 /// ```
1479 ///
1480 /// Handling lag
1481 ///
1482 /// ```
1483 /// use tokio::sync::broadcast;
1484 /// use tokio::sync::broadcast::error::RecvError;
1485 ///
1486 /// # #[tokio::main(flavor = "current_thread")]
1487 /// # async fn main() {
1488 /// let (tx, mut rx) = broadcast::channel(2);
1489 ///
1490 /// tx.send(10).unwrap();
1491 /// tx.send(20).unwrap();
1492 /// tx.send(30).unwrap();
1493 ///
1494 /// // One message was overwritten before this receiver could read it.
1495 /// assert!(matches!(rx.recv().await, Err(RecvError::Lagged(1))));
1496 ///
1497 /// // Resume from the oldest retained message, or abort the task instead.
1498 /// assert_eq!(20, rx.recv().await.unwrap());
1499 /// assert_eq!(30, rx.recv().await.unwrap());
1500 /// # }
1501 /// ```
1502 pub async fn recv(&mut self) -> Result<T, RecvError> {
1503 cooperative(Recv::new(self)).await
1504 }
1505
1506 /// Attempts to return a pending value on this receiver without awaiting.
1507 ///
1508 /// This is useful for a flavor of "optimistic check" before deciding to
1509 /// await on a receiver.
1510 ///
1511 /// Compared with [`recv`], this function has three failure cases instead of two
1512 /// (one for closed, one for an empty buffer, one for a lagging receiver).
1513 ///
1514 /// `Err(TryRecvError::Closed)` is returned when all `Sender` halves have
1515 /// dropped, indicating that no further values can be sent on the channel.
1516 ///
1517 /// If the [`Receiver`] handle falls behind, once the channel is full, newly
1518 /// sent values overwrite old values in the ring buffer. The next call to
1519 /// [`try_recv`] then returns `Err(TryRecvError::Lagged(n))`, where `n` is
1520 /// the number of overwritten messages the receiver missed. The receiver
1521 /// stays subscribed; its internal cursor is advanced to the oldest value
1522 /// still held by the channel. A subsequent call to [`try_recv`] returns
1523 /// that value, unless further sends overwrite it before the receiver reads
1524 /// it. If there are no values to receive, `Err(TryRecvError::Empty)` is
1525 /// returned. See [lagging](self#lagging) for details.
1526 ///
1527 /// [`recv`]: crate::sync::broadcast::Receiver::recv
1528 /// [`try_recv`]: crate::sync::broadcast::Receiver::try_recv
1529 /// [`Receiver`]: crate::sync::broadcast::Receiver
1530 ///
1531 /// # Examples
1532 ///
1533 /// ```
1534 /// use tokio::sync::broadcast;
1535 ///
1536 /// # #[tokio::main(flavor = "current_thread")]
1537 /// # async fn main() {
1538 /// let (tx, mut rx) = broadcast::channel(16);
1539 ///
1540 /// assert!(rx.try_recv().is_err());
1541 ///
1542 /// tx.send(10).unwrap();
1543 ///
1544 /// let value = rx.try_recv().unwrap();
1545 /// assert_eq!(10, value);
1546 /// # }
1547 /// ```
1548 pub fn try_recv(&mut self) -> Result<T, TryRecvError> {
1549 let guard = self.recv_ref(None)?;
1550 guard.clone_value().ok_or(TryRecvError::Closed)
1551 }
1552
1553 /// Blocking receive to call outside of asynchronous contexts.
1554 ///
1555 /// # Panics
1556 ///
1557 /// This function panics if called within an asynchronous execution
1558 /// context.
1559 ///
1560 /// # Examples
1561 /// ```
1562 /// # #[cfg(not(target_family = "wasm"))]
1563 /// # {
1564 /// use std::thread;
1565 /// use tokio::sync::broadcast;
1566 ///
1567 /// #[tokio::main]
1568 /// async fn main() {
1569 /// let (tx, mut rx) = broadcast::channel(16);
1570 ///
1571 /// let sync_code = thread::spawn(move || {
1572 /// assert_eq!(rx.blocking_recv(), Ok(10));
1573 /// });
1574 ///
1575 /// let _ = tx.send(10);
1576 /// sync_code.join().unwrap();
1577 /// }
1578 /// # }
1579 /// ```
1580 pub fn blocking_recv(&mut self) -> Result<T, RecvError> {
1581 crate::future::block_on(self.recv())
1582 }
1583}
1584
1585impl<T> Drop for Receiver<T> {
1586 fn drop(&mut self) {
1587 struct NotifyGuard<'a, T> {
1588 rx: &'a mut Receiver<T>,
1589 notify: bool,
1590 }
1591
1592 impl<T> Drop for NotifyGuard<'_, T> {
1593 fn drop(&mut self) {
1594 if self.notify {
1595 self.rx.shared.notify_last_rx_drop.notify_waiters();
1596 }
1597 }
1598 }
1599
1600 let mut tail = self.shared.tail.lock();
1601
1602 tail.rx_cnt -= 1;
1603 let until = tail.pos;
1604 let remaining_rx = tail.rx_cnt;
1605
1606 if remaining_rx == 0 {
1607 tail.closed = true;
1608 }
1609
1610 drop(tail);
1611
1612 let guard = NotifyGuard {
1613 rx: self,
1614 notify: remaining_rx == 0,
1615 };
1616
1617 while guard.rx.next < until {
1618 match guard.rx.recv_ref(None) {
1619 Ok(_) => {}
1620 // The channel is closed
1621 Err(TryRecvError::Closed) => break,
1622 // Ignore lagging, we will catch up
1623 Err(TryRecvError::Lagged(..)) => {}
1624 // Can't be empty
1625 Err(TryRecvError::Empty) => panic!("unexpected empty broadcast channel"),
1626 }
1627 }
1628 }
1629}
1630
1631impl<'a, T> Recv<'a, T> {
1632 fn new(receiver: &'a mut Receiver<T>) -> Recv<'a, T> {
1633 Recv {
1634 receiver,
1635 waiter: WaiterCell(UnsafeCell::new(Waiter {
1636 queued: AtomicBool::new(false),
1637 waker: None,
1638 pointers: linked_list::Pointers::new(),
1639 _p: PhantomPinned,
1640 })),
1641 }
1642 }
1643
1644 /// A custom `project` implementation is used in place of `pin-project-lite`
1645 /// as a custom drop implementation is needed.
1646 fn project(self: Pin<&mut Self>) -> (&mut Receiver<T>, &UnsafeCell<Waiter>) {
1647 unsafe {
1648 // Safety: Receiver is Unpin
1649 is_unpin::<&mut Receiver<T>>();
1650
1651 let me = self.get_unchecked_mut();
1652 (me.receiver, &me.waiter.0)
1653 }
1654 }
1655}
1656
1657impl<'a, T> Future for Recv<'a, T>
1658where
1659 T: Clone,
1660{
1661 type Output = Result<T, RecvError>;
1662
1663 fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<T, RecvError>> {
1664 ready!(crate::trace::trace_leaf(cx));
1665
1666 let (receiver, waiter) = self.project();
1667
1668 let guard = match receiver.recv_ref(Some((waiter, cx.waker()))) {
1669 Ok(value) => value,
1670 Err(TryRecvError::Empty) => return Poll::Pending,
1671 Err(TryRecvError::Lagged(n)) => return Poll::Ready(Err(RecvError::Lagged(n))),
1672 Err(TryRecvError::Closed) => return Poll::Ready(Err(RecvError::Closed)),
1673 };
1674
1675 Poll::Ready(guard.clone_value().ok_or(RecvError::Closed))
1676 }
1677}
1678
1679impl<'a, T> Drop for Recv<'a, T> {
1680 fn drop(&mut self) {
1681 // Safety: `waiter.queued` is atomic.
1682 // Acquire ordering is required to synchronize with
1683 // `Shared::notify_rx` before we drop the object.
1684 let queued = self
1685 .waiter
1686 .0
1687 .with(|ptr| unsafe { (*ptr).queued.load(Acquire) });
1688
1689 // If the waiter is queued, we need to unlink it from the waiters list.
1690 // If not, no further synchronization is required, since the waiter
1691 // is not in the list and, as such, is not shared with any other threads.
1692 if queued {
1693 // Acquire the tail lock. This is required for safety before accessing
1694 // the waiter node.
1695 let mut tail = self.receiver.shared.tail.lock();
1696
1697 // Safety: tail lock is held.
1698 // `Relaxed` order suffices because we hold the tail lock.
1699 let queued = self
1700 .waiter
1701 .0
1702 .with_mut(|ptr| unsafe { (*ptr).queued.load(Relaxed) });
1703
1704 if queued {
1705 // Remove the node
1706 //
1707 // safety: tail lock is held and the wait node is verified to be in
1708 // the list.
1709 unsafe {
1710 self.waiter.0.with_mut(|ptr| {
1711 tail.waiters.remove((&mut *ptr).into());
1712 });
1713 }
1714 }
1715 }
1716 }
1717}
1718
1719/// # Safety
1720///
1721/// `Waiter` is forced to be !Unpin.
1722unsafe impl linked_list::Link for Waiter {
1723 type Handle = NonNull<Waiter>;
1724 type Target = Waiter;
1725
1726 fn as_raw(handle: &NonNull<Waiter>) -> NonNull<Waiter> {
1727 *handle
1728 }
1729
1730 unsafe fn from_raw(ptr: NonNull<Waiter>) -> NonNull<Waiter> {
1731 ptr
1732 }
1733
1734 unsafe fn pointers(target: NonNull<Waiter>) -> NonNull<linked_list::Pointers<Waiter>> {
1735 unsafe { Waiter::addr_of_pointers(target) }
1736 }
1737}
1738
1739impl<T> fmt::Debug for Sender<T> {
1740 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1741 write!(fmt, "broadcast::Sender")
1742 }
1743}
1744
1745impl<T> fmt::Debug for WeakSender<T> {
1746 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1747 write!(fmt, "broadcast::WeakSender")
1748 }
1749}
1750
1751impl<T> fmt::Debug for Receiver<T> {
1752 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
1753 write!(fmt, "broadcast::Receiver")
1754 }
1755}
1756
1757impl<'a, T> RecvGuard<'a, T> {
1758 fn clone_value(&self) -> Option<T>
1759 where
1760 T: Clone,
1761 {
1762 self.slot.val.clone()
1763 }
1764}
1765
1766impl<'a, T> Drop for RecvGuard<'a, T> {
1767 fn drop(&mut self) {
1768 // Decrement the remaining counter
1769 self.slot.rem -= 1;
1770 if self.slot.rem == 0 {
1771 self.slot.val = None;
1772 }
1773 }
1774}
1775
1776fn is_unpin<T: Unpin>() {}
1777
1778#[cfg(not(loom))]
1779#[cfg(test)]
1780mod tests {
1781 use super::*;
1782
1783 #[test]
1784 fn receiver_count_on_sender_constructor() {
1785 let sender = Sender::<i32>::new(16);
1786 assert_eq!(sender.receiver_count(), 0);
1787
1788 let rx_1 = sender.subscribe();
1789 assert_eq!(sender.receiver_count(), 1);
1790
1791 let rx_2 = rx_1.resubscribe();
1792 assert_eq!(sender.receiver_count(), 2);
1793
1794 let rx_3 = sender.subscribe();
1795 assert_eq!(sender.receiver_count(), 3);
1796
1797 drop(rx_3);
1798 drop(rx_1);
1799 assert_eq!(sender.receiver_count(), 1);
1800
1801 drop(rx_2);
1802 assert_eq!(sender.receiver_count(), 0);
1803 }
1804
1805 #[cfg(not(loom))]
1806 #[test]
1807 fn receiver_count_on_channel_constructor() {
1808 let (sender, rx) = channel::<i32>(16);
1809 assert_eq!(sender.receiver_count(), 1);
1810
1811 let _rx_2 = rx.resubscribe();
1812 assert_eq!(sender.receiver_count(), 2);
1813 }
1814}