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.
This commit is contained in:
Sören Meier 2024-10-11 04:31:11 +02:00 committed by GitHub
parent 679d7657dc
commit 9cc4a81678
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1336,6 +1336,29 @@ impl<T> Sender<T> {
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