Skip to content

Commit

Permalink
sync: add same_channel method to mpsc Senders (#3532)
Browse files Browse the repository at this point in the history
  • Loading branch information
zh-jq committed Mar 4, 2021
1 parent 0867a6f commit e06b257
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
16 changes: 16 additions & 0 deletions tokio/src/sync/mpsc/bounded.rs
Expand Up @@ -698,6 +698,22 @@ impl<T> Sender<T> {

Ok(Permit { chan: &self.chan })
}

/// Returns `true` if senders belong to the same channel.
///
/// # Examples
///
/// ```
/// let (tx, rx) = tokio::sync::mpsc::channel::<()>(1);
/// let tx2 = tx.clone();
/// assert!(tx.same_channel(&tx2));
///
/// let (tx3, rx3) = tokio::sync::mpsc::channel::<()>(1);
/// assert!(!tx3.same_channel(&tx2));
/// ```
pub fn same_channel(&self, other: &Self) -> bool {
self.chan.same_channel(&other.chan)
}
}

impl<T> Clone for Sender<T> {
Expand Down
5 changes: 5 additions & 0 deletions tokio/src/sync/mpsc/chan.rs
Expand Up @@ -139,6 +139,11 @@ impl<T, S> Tx<T, S> {
pub(crate) fn wake_rx(&self) {
self.inner.rx_waker.wake();
}

/// Returns `true` if senders belong to the same channel.
pub(crate) fn same_channel(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.inner, &other.inner)
}
}

impl<T, S: Semaphore> Tx<T, S> {
Expand Down
16 changes: 16 additions & 0 deletions tokio/src/sync/mpsc/unbounded.rs
Expand Up @@ -291,4 +291,20 @@ impl<T> UnboundedSender<T> {
pub fn is_closed(&self) -> bool {
self.chan.is_closed()
}

/// Returns `true` if senders belong to the same channel.
///
/// # Examples
///
/// ```
/// let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<()>();
/// let tx2 = tx.clone();
/// assert!(tx.same_channel(&tx2));
///
/// let (tx3, rx3) = tokio::sync::mpsc::unbounded_channel::<()>();
/// assert!(!tx3.same_channel(&tx2));
/// ```
pub fn same_channel(&self, other: &Self) -> bool {
self.chan.same_channel(&other.chan)
}
}

0 comments on commit e06b257

Please sign in to comment.