From 9cc4a81678ffb423cf89c12b08241272c1b6ecb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B6ren=20Meier?= Date: Fri, 11 Oct 2024 04:31:11 +0200 Subject: [PATCH] sync: add `watch::Sender::sender_count` (#6836) This makes it possible to check if other senders exist. For example If you are using a Sender as a subscriber to get a Receiver and might want to know if the real sender is still running. --- tokio/src/sync/watch.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/tokio/src/sync/watch.rs b/tokio/src/sync/watch.rs index af72e30dd..7d042a6f9 100644 --- a/tokio/src/sync/watch.rs +++ b/tokio/src/sync/watch.rs @@ -1336,6 +1336,29 @@ impl Sender { self.shared.ref_count_rx.load(Relaxed) } + /// Returns the number of senders that currently exist. + /// + /// # Examples + /// + /// ``` + /// use tokio::sync::watch; + /// + /// #[tokio::main] + /// async fn main() { + /// let (tx1, rx) = watch::channel("hello"); + /// + /// assert_eq!(1, tx1.sender_count()); + /// + /// let tx2 = tx1.clone(); + /// + /// assert_eq!(2, tx1.sender_count()); + /// assert_eq!(2, tx2.sender_count()); + /// } + /// ``` + pub fn sender_count(&self) -> usize { + self.shared.ref_count_tx.load(Relaxed) + } + /// Returns `true` if senders belong to the same channel. /// /// # Examples