| 1 |
#![cfg_attr(not(feature = "sync"), allow(dead_code, unreachable_pub))] |
| 2 |
|
| 3 |
//! A multi-producer, multi-consumer channel that only retains the *last* sent |
| 4 |
//! value. |
| 5 |
//! |
| 6 |
//! This channel is useful for watching for changes to a value from multiple |
| 7 |
//! points in the code base, for example, changes to configuration values. |
| 8 |
//! |
| 9 |
//! # Usage |
| 10 |
//! |
| 11 |
//! [`channel`] returns a [`Sender`] / [`Receiver`] pair. These are the producer |
| 12 |
//! and consumer halves of the channel. The channel is created with an initial |
| 13 |
//! value. |
| 14 |
//! |
| 15 |
//! Each [`Receiver`] independently tracks the last value *seen* by its caller. |
| 16 |
//! |
| 17 |
//! To access the **current** value stored in the channel and mark it as *seen* |
| 18 |
//! by a given [`Receiver`], use [`Receiver::borrow_and_update()`]. |
| 19 |
//! |
| 20 |
//! To access the current value **without** marking it as *seen*, use |
| 21 |
//! [`Receiver::borrow()`]. (If the value has already been marked *seen*, |
| 22 |
//! [`Receiver::borrow()`] is equivalent to [`Receiver::borrow_and_update()`].) |
| 23 |
//! |
| 24 |
//! For more information on when to use these methods, see |
| 25 |
//! [here](#borrow_and_update-versus-borrow). |
| 26 |
//! |
| 27 |
//! ## Change notifications |
| 28 |
//! |
| 29 |
//! The [`Receiver`] half provides an asynchronous [`changed`] method. This |
| 30 |
//! method is ready when a new, *unseen* value is sent via the [`Sender`] half. |
| 31 |
//! |
| 32 |
//! * [`Receiver::changed()`] returns `Ok(())` on receiving a new value, or |
| 33 |
//! `Err(`[`error::RecvError`]`)` if the [`Sender`] has been dropped. |
| 34 |
//! * If the current value is *unseen* when calling [`changed`], then |
| 35 |
//! [`changed`] will return immediately. If the current value is *seen*, then |
| 36 |
//! it will sleep until either a new message is sent via the [`Sender`] half, |
| 37 |
//! or the [`Sender`] is dropped. |
| 38 |
//! * On completion, the [`changed`] method marks the new value as *seen*. |
| 39 |
//! * At creation, the initial value is considered *seen*. In other words, |
| 40 |
//! [`Receiver::changed()`] will not return until a subsequent value is sent. |
| 41 |
//! * New [`Receiver`] instances can be created with [`Sender::subscribe()`]. |
| 42 |
//! The current value at the time the [`Receiver`] is created is considered |
| 43 |
//! *seen*. |
| 44 |
//! |
| 45 |
//! ## `borrow_and_update` versus `borrow` |
| 46 |
//! |
| 47 |
//! If the receiver intends to await notifications from [`changed`] in a loop, |
| 48 |
//! [`Receiver::borrow_and_update()`] should be preferred over |
| 49 |
//! [`Receiver::borrow()`]. This avoids a potential race where a new value is |
| 50 |
//! sent between [`changed`] being ready and the value being read. (If |
| 51 |
//! [`Receiver::borrow()`] is used, the loop may run twice with the same value.) |
| 52 |
//! |
| 53 |
//! If the receiver is only interested in the current value, and does not intend |
| 54 |
//! to wait for changes, then [`Receiver::borrow()`] can be used. It may be more |
| 55 |
//! convenient to use [`borrow`](Receiver::borrow) since it's an `&self` |
| 56 |
//! method---[`borrow_and_update`](Receiver::borrow_and_update) requires `&mut |
| 57 |
//! self`. |
| 58 |
//! |
| 59 |
//! # Examples |
| 60 |
//! |
| 61 |
//! The following example prints `hello! world! `. |
| 62 |
//! |
| 63 |
//! ``` |
| 64 |
//! use tokio::sync::watch; |
| 65 |
//! use tokio::time::{Duration, sleep}; |
| 66 |
//! |
| 67 |
//! # async fn dox() -> Result<(), Box<dyn std::error::Error>> { |
| 68 |
//! let (tx, mut rx) = watch::channel("hello"); |
| 69 |
//! |
| 70 |
//! tokio::spawn(async move { |
| 71 |
//! // Use the equivalent of a "do-while" loop so the initial value is |
| 72 |
//! // processed before awaiting the `changed()` future. |
| 73 |
//! loop { |
| 74 |
//! println!("{}! ", *rx.borrow_and_update()); |
| 75 |
//! if rx.changed().await.is_err() { |
| 76 |
//! break; |
| 77 |
//! } |
| 78 |
//! } |
| 79 |
//! }); |
| 80 |
//! |
| 81 |
//! sleep(Duration::from_millis(100)).await; |
| 82 |
//! tx.send("world")?; |
| 83 |
//! # Ok(()) |
| 84 |
//! # } |
| 85 |
//! ``` |
| 86 |
//! |
| 87 |
//! # Closing |
| 88 |
//! |
| 89 |
//! [`Sender::is_closed`] and [`Sender::closed`] allow the producer to detect |
| 90 |
//! when all [`Receiver`] handles have been dropped. This indicates that there |
| 91 |
//! is no further interest in the values being produced and work can be stopped. |
| 92 |
//! |
| 93 |
//! The value in the channel will not be dropped until the sender and all |
| 94 |
//! receivers have been dropped. |
| 95 |
//! |
| 96 |
//! # Thread safety |
| 97 |
//! |
| 98 |
//! Both [`Sender`] and [`Receiver`] are thread safe. They can be moved to other |
| 99 |
//! threads and can be used in a concurrent environment. Clones of [`Receiver`] |
| 100 |
//! handles may be moved to separate threads and also used concurrently. |
| 101 |
//! |
| 102 |
//! [`Sender`]: crate::sync::watch::Sender |
| 103 |
//! [`Receiver`]: crate::sync::watch::Receiver |
| 104 |
//! [`changed`]: crate::sync::watch::Receiver::changed |
| 105 |
//! [`Receiver::changed()`]: crate::sync::watch::Receiver::changed |
| 106 |
//! [`Receiver::borrow()`]: crate::sync::watch::Receiver::borrow |
| 107 |
//! [`Receiver::borrow_and_update()`]: |
| 108 |
//! crate::sync::watch::Receiver::borrow_and_update |
| 109 |
//! [`channel`]: crate::sync::watch::channel |
| 110 |
//! [`Sender::is_closed`]: crate::sync::watch::Sender::is_closed |
| 111 |
//! [`Sender::closed`]: crate::sync::watch::Sender::closed |
| 112 |
//! [`Sender::subscribe()`]: crate::sync::watch::Sender::subscribe |
| 113 |
|
| 114 |
use crate::sync::notify::Notify; |
| 115 |
|
| 116 |
use crate::loom::sync::atomic::AtomicUsize; |
| 117 |
use crate::loom::sync::atomic::Ordering::{AcqRel, Relaxed}; |
| 118 |
use crate::loom::sync::{Arc, RwLock, RwLockReadGuard}; |
| 119 |
use std::fmt; |
| 120 |
use std::mem; |
| 121 |
use std::ops; |
| 122 |
use std::panic; |
| 123 |
|
| 124 |
/// Receives values from the associated [`Sender`](struct@Sender). |
| 125 |
/// |
| 126 |
/// Instances are created by the [`channel`](fn@channel) function. |
| 127 |
/// |
| 128 |
/// To turn this receiver into a `Stream`, you can use the [`WatchStream`] |
| 129 |
/// wrapper. |
| 130 |
/// |
| 131 |
/// [`WatchStream`]: https://docs.rs/tokio-stream/0.1/tokio_stream/wrappers/struct.WatchStream.html |
| 132 |
#[derive(Debug)] |
| 133 |
pub struct Receiver<T> { |
| 134 |
/// Pointer to the shared state |
| 135 |
shared: Arc<Shared<T>>, |
| 136 |
|
| 137 |
/// Last observed version |
| 138 |
version: Version, |
| 139 |
} |
| 140 |
|
| 141 |
/// Sends values to the associated [`Receiver`](struct@Receiver). |
| 142 |
/// |
| 143 |
/// Instances are created by the [`channel`](fn@channel) function. |
| 144 |
#[derive(Debug)] |
| 145 |
pub struct Sender<T> { |
| 146 |
shared: Arc<Shared<T>>, |
| 147 |
} |
| 148 |
|
| 149 |
impl<T> Clone for Sender<T> { |
| 150 |
fn clone(&self) -> Self { |
| 151 |
self.shared.ref_count_tx.fetch_add(1, Relaxed); |
| 152 |
|
| 153 |
Self { |
| 154 |
shared: self.shared.clone(), |
| 155 |
} |
| 156 |
} |
| 157 |
} |
| 158 |
|
| 159 |
impl<T: Default> Default for Sender<T> { |
| 160 |
fn default() -> Self { |
| 161 |
Self::new(T::default()) |
| 162 |
} |
| 163 |
} |
| 164 |
|
| 165 |
/// Returns a reference to the inner value. |
| 166 |
/// |
| 167 |
/// Outstanding borrows hold a read lock on the inner value. This means that |
| 168 |
/// long-lived borrows could cause the producer half to block. It is recommended |
| 169 |
/// to keep the borrow as short-lived as possible. Additionally, if you are |
| 170 |
/// running in an environment that allows `!Send` futures, you must ensure that |
| 171 |
/// the returned `Ref` type is never held alive across an `.await` point, |
| 172 |
/// otherwise, it can lead to a deadlock. |
| 173 |
/// |
| 174 |
/// The priority policy of the lock is dependent on the underlying lock |
| 175 |
/// implementation, and this type does not guarantee that any particular policy |
| 176 |
/// will be used. In particular, a producer which is waiting to acquire the lock |
| 177 |
/// in `send` might or might not block concurrent calls to `borrow`, e.g.: |
| 178 |
/// |
| 179 |
/// <details><summary>Potential deadlock example</summary> |
| 180 |
/// |
| 181 |
/// ```text |
| 182 |
/// // Task 1 (on thread A) | // Task 2 (on thread B) |
| 183 |
/// let _ref1 = rx.borrow(); | |
| 184 |
/// | // will block |
| 185 |
/// | let _ = tx.send(()); |
| 186 |
/// // may deadlock | |
| 187 |
/// let _ref2 = rx.borrow(); | |
| 188 |
/// ``` |
| 189 |
/// </details> |
| 190 |
#[derive(Debug)] |
| 191 |
pub struct Ref<'a, T> { |
| 192 |
inner: RwLockReadGuard<'a, T>, |
| 193 |
has_changed: bool, |
| 194 |
} |
| 195 |
|
| 196 |
impl<'a, T> Ref<'a, T> { |
| 197 |
/// Indicates if the borrowed value is considered as _changed_ since the last |
| 198 |
/// time it has been marked as seen. |
| 199 |
/// |
| 200 |
/// Unlike [`Receiver::has_changed()`], this method does not fail if the channel is closed. |
| 201 |
/// |
| 202 |
/// When borrowed from the [`Sender`] this function will always return `false`. |
| 203 |
/// |
| 204 |
/// # Examples |
| 205 |
/// |
| 206 |
/// ``` |
| 207 |
/// use tokio::sync::watch; |
| 208 |
/// |
| 209 |
/// #[tokio::main] |
| 210 |
/// async fn main() { |
| 211 |
/// let (tx, mut rx) = watch::channel("hello"); |
| 212 |
/// |
| 213 |
/// tx.send("goodbye").unwrap(); |
| 214 |
/// // The sender does never consider the value as changed. |
| 215 |
/// assert!(!tx.borrow().has_changed()); |
| 216 |
/// |
| 217 |
/// // Drop the sender immediately, just for testing purposes. |
| 218 |
/// drop(tx); |
| 219 |
/// |
| 220 |
/// // Even if the sender has already been dropped... |
| 221 |
/// assert!(rx.has_changed().is_err()); |
| 222 |
/// // ...the modified value is still readable and detected as changed. |
| 223 |
/// assert_eq!(*rx.borrow(), "goodbye"); |
| 224 |
/// assert!(rx.borrow().has_changed()); |
| 225 |
/// |
| 226 |
/// // Read the changed value and mark it as seen. |
| 227 |
/// { |
| 228 |
/// let received = rx.borrow_and_update(); |
| 229 |
/// assert_eq!(*received, "goodbye"); |
| 230 |
/// assert!(received.has_changed()); |
| 231 |
/// // Release the read lock when leaving this scope. |
| 232 |
/// } |
| 233 |
/// |
| 234 |
/// // Now the value has already been marked as seen and could |
| 235 |
/// // never be modified again (after the sender has been dropped). |
| 236 |
/// assert!(!rx.borrow().has_changed()); |
| 237 |
/// } |
| 238 |
/// ``` |
| 239 |
pub fn has_changed(&self) -> bool { |
| 240 |
self.has_changed |
| 241 |
} |
| 242 |
} |
| 243 |
|
| 244 |
struct Shared<T> { |
| 245 |
/// The most recent value. |
| 246 |
value: RwLock<T>, |
| 247 |
|
| 248 |
/// The current version. |
| 249 |
/// |
| 250 |
/// The lowest bit represents a "closed" state. The rest of the bits |
| 251 |
/// represent the current version. |
| 252 |
state: AtomicState, |
| 253 |
|
| 254 |
/// Tracks the number of `Receiver` instances. |
| 255 |
ref_count_rx: AtomicUsize, |
| 256 |
|
| 257 |
/// Tracks the number of `Sender` instances. |
| 258 |
ref_count_tx: AtomicUsize, |
| 259 |
|
| 260 |
/// Notifies waiting receivers that the value changed. |
| 261 |
notify_rx: big_notify::BigNotify, |
| 262 |
|
| 263 |
/// Notifies any task listening for `Receiver` dropped events. |
| 264 |
notify_tx: Notify, |
| 265 |
} |
| 266 |
|
| 267 |
impl<T: fmt::Debug> fmt::Debug for Shared<T> { |
| 268 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 269 |
let state = self.state.load(); |
| 270 |
f.debug_struct("Shared") |
| 271 |
.field("value", &self.value) |
| 272 |
.field("version", &state.version()) |
| 273 |
.field("is_closed", &state.is_closed()) |
| 274 |
.field("ref_count_rx", &self.ref_count_rx) |
| 275 |
.finish() |
| 276 |
} |
| 277 |
} |
| 278 |
|
| 279 |
pub mod error { |
| 280 |
//! Watch error types. |
| 281 |
|
| 282 |
use std::error::Error; |
| 283 |
use std::fmt; |
| 284 |
|
| 285 |
/// Error produced when sending a value fails. |
| 286 |
#[derive(PartialEq, Eq, Clone, Copy)] |
| 287 |
pub struct SendError<T>(pub T); |
| 288 |
|
| 289 |
// ===== impl SendError ===== |
| 290 |
|
| 291 |
impl<T> fmt::Debug for SendError<T> { |
| 292 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 293 |
f.debug_struct("SendError").finish_non_exhaustive() |
| 294 |
} |
| 295 |
} |
| 296 |
|
| 297 |
impl<T> fmt::Display for SendError<T> { |
| 298 |
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 299 |
write!(fmt, "channel closed") |
| 300 |
} |
| 301 |
} |
| 302 |
|
| 303 |
impl<T> Error for SendError<T> {} |
| 304 |
|
| 305 |
/// Error produced when receiving a change notification. |
| 306 |
#[derive(Debug, Clone)] |
| 307 |
pub struct RecvError(pub(super) ()); |
| 308 |
|
| 309 |
// ===== impl RecvError ===== |
| 310 |
|
| 311 |
impl fmt::Display for RecvError { |
| 312 |
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 313 |
write!(fmt, "channel closed") |
| 314 |
} |
| 315 |
} |
| 316 |
|
| 317 |
impl Error for RecvError {} |
| 318 |
} |
| 319 |
|
| 320 |
mod big_notify { |
| 321 |
use super::Notify; |
| 322 |
use crate::sync::notify::Notified; |
| 323 |
|
| 324 |
// To avoid contention on the lock inside the `Notify`, we store multiple |
| 325 |
// copies of it. Then, we use either circular access or randomness to spread |
| 326 |
// out threads over different `Notify` objects. |
| 327 |
// |
| 328 |
// Some simple benchmarks show that randomness performs slightly better than |
| 329 |
// circular access (probably due to contention on `next`), so we prefer to |
| 330 |
// use randomness when Tokio is compiled with a random number generator. |
| 331 |
// |
| 332 |
// When the random number generator is not available, we fall back to |
| 333 |
// circular access. |
| 334 |
|
| 335 |
pub(super) struct BigNotify { |
| 336 |
#[cfg(not(all(not(loom), feature = "sync", any(feature = "rt", feature = "macros"))))] |
| 337 |
next: std::sync::atomic::AtomicUsize, |
| 338 |
inner: [Notify; 8], |
| 339 |
} |
| 340 |
|
| 341 |
impl BigNotify { |
| 342 |
pub(super) fn new() -> Self { |
| 343 |
Self { |
| 344 |
#[cfg(not(all( |
| 345 |
not(loom), |
| 346 |
feature = "sync", |
| 347 |
any(feature = "rt", feature = "macros") |
| 348 |
)))] |
| 349 |
next: std::sync::atomic::AtomicUsize::new(0), |
| 350 |
inner: Default::default(), |
| 351 |
} |
| 352 |
} |
| 353 |
|
| 354 |
pub(super) fn notify_waiters(&self) { |
| 355 |
for notify in &self.inner { |
| 356 |
notify.notify_waiters(); |
| 357 |
} |
| 358 |
} |
| 359 |
|
| 360 |
/// This function implements the case where randomness is not available. |
| 361 |
#[cfg(not(all(not(loom), feature = "sync", any(feature = "rt", feature = "macros"))))] |
| 362 |
pub(super) fn notified(&self) -> Notified<'_> { |
| 363 |
let i = self.next.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 8; |
| 364 |
self.inner[i].notified() |
| 365 |
} |
| 366 |
|
| 367 |
/// This function implements the case where randomness is available. |
| 368 |
#[cfg(all(not(loom), feature = "sync", any(feature = "rt", feature = "macros")))] |
| 369 |
pub(super) fn notified(&self) -> Notified<'_> { |
| 370 |
let i = crate::runtime::context::thread_rng_n(8) as usize; |
| 371 |
self.inner[i].notified() |
| 372 |
} |
| 373 |
} |
| 374 |
} |
| 375 |
|
| 376 |
use self::state::{AtomicState, Version}; |
| 377 |
mod state { |
| 378 |
use crate::loom::sync::atomic::AtomicUsize; |
| 379 |
use crate::loom::sync::atomic::Ordering; |
| 380 |
|
| 381 |
const CLOSED_BIT: usize = 1; |
| 382 |
|
| 383 |
// Using 2 as the step size preserves the `CLOSED_BIT`. |
| 384 |
const STEP_SIZE: usize = 2; |
| 385 |
|
| 386 |
/// The version part of the state. The lowest bit is always zero. |
| 387 |
#[derive(Copy, Clone, Debug, Eq, PartialEq)] |
| 388 |
pub(super) struct Version(usize); |
| 389 |
|
| 390 |
/// Snapshot of the state. The first bit is used as the CLOSED bit. |
| 391 |
/// The remaining bits are used as the version. |
| 392 |
/// |
| 393 |
/// The CLOSED bit tracks whether the Sender has been dropped. Dropping all |
| 394 |
/// receivers does not set it. |
| 395 |
#[derive(Copy, Clone, Debug)] |
| 396 |
pub(super) struct StateSnapshot(usize); |
| 397 |
|
| 398 |
/// The state stored in an atomic integer. |
| 399 |
/// |
| 400 |
/// The `Sender` uses `Release` ordering for storing a new state |
| 401 |
/// and the `Receiver`s use `Acquire` ordering for loading the |
| 402 |
/// current state. This ensures that written values are seen by |
| 403 |
/// the `Receiver`s for a proper handover. |
| 404 |
#[derive(Debug)] |
| 405 |
pub(super) struct AtomicState(AtomicUsize); |
| 406 |
|
| 407 |
impl Version { |
| 408 |
/// Decrements the version. |
| 409 |
pub(super) fn decrement(&mut self) { |
| 410 |
// Using a wrapping decrement here is required to ensure that the |
| 411 |
// operation is consistent with `std::sync::atomic::AtomicUsize::fetch_add()` |
| 412 |
// which wraps on overflow. |
| 413 |
self.0 = self.0.wrapping_sub(STEP_SIZE); |
| 414 |
} |
| 415 |
|
| 416 |
pub(super) const INITIAL: Self = Version(0); |
| 417 |
} |
| 418 |
|
| 419 |
impl StateSnapshot { |
| 420 |
/// Extract the version from the state. |
| 421 |
pub(super) fn version(self) -> Version { |
| 422 |
Version(self.0 & !CLOSED_BIT) |
| 423 |
} |
| 424 |
|
| 425 |
/// Is the closed bit set? |
| 426 |
pub(super) fn is_closed(self) -> bool { |
| 427 |
(self.0 & CLOSED_BIT) == CLOSED_BIT |
| 428 |
} |
| 429 |
} |
| 430 |
|
| 431 |
impl AtomicState { |
| 432 |
/// Create a new `AtomicState` that is not closed and which has the |
| 433 |
/// version set to `Version::INITIAL`. |
| 434 |
pub(super) fn new() -> Self { |
| 435 |
AtomicState(AtomicUsize::new(Version::INITIAL.0)) |
| 436 |
} |
| 437 |
|
| 438 |
/// Load the current value of the state. |
| 439 |
/// |
| 440 |
/// Only used by the receiver and for debugging purposes. |
| 441 |
/// |
| 442 |
/// The receiver side (read-only) uses `Acquire` ordering for a proper handover |
| 443 |
/// of the shared value with the sender side (single writer). The state is always |
| 444 |
/// updated after modifying and before releasing the (exclusive) lock on the |
| 445 |
/// shared value. |
| 446 |
pub(super) fn load(&self) -> StateSnapshot { |
| 447 |
StateSnapshot(self.0.load(Ordering::Acquire)) |
| 448 |
} |
| 449 |
|
| 450 |
/// Increment the version counter. |
| 451 |
pub(super) fn increment_version_while_locked(&self) { |
| 452 |
// Use `Release` ordering to ensure that the shared value |
| 453 |
// has been written before updating the version. The shared |
| 454 |
// value is still protected by an exclusive lock during this |
| 455 |
// method. |
| 456 |
self.0.fetch_add(STEP_SIZE, Ordering::Release); |
| 457 |
} |
| 458 |
|
| 459 |
/// Set the closed bit in the state. |
| 460 |
pub(super) fn set_closed(&self) { |
| 461 |
self.0.fetch_or(CLOSED_BIT, Ordering::Release); |
| 462 |
} |
| 463 |
} |
| 464 |
} |
| 465 |
|
| 466 |
/// Creates a new watch channel, returning the "send" and "receive" handles. |
| 467 |
/// |
| 468 |
/// All values sent by [`Sender`] will become visible to the [`Receiver`] handles. |
| 469 |
/// Only the last value sent is made available to the [`Receiver`] half. All |
| 470 |
/// intermediate values are dropped. |
| 471 |
/// |
| 472 |
/// # Examples |
| 473 |
/// |
| 474 |
/// The following example prints `hello! world! `. |
| 475 |
/// |
| 476 |
/// ``` |
| 477 |
/// use tokio::sync::watch; |
| 478 |
/// use tokio::time::{Duration, sleep}; |
| 479 |
/// |
| 480 |
/// # async fn dox() -> Result<(), Box<dyn std::error::Error>> { |
| 481 |
/// let (tx, mut rx) = watch::channel("hello"); |
| 482 |
/// |
| 483 |
/// tokio::spawn(async move { |
| 484 |
/// // Use the equivalent of a "do-while" loop so the initial value is |
| 485 |
/// // processed before awaiting the `changed()` future. |
| 486 |
/// loop { |
| 487 |
/// println!("{}! ", *rx.borrow_and_update()); |
| 488 |
/// if rx.changed().await.is_err() { |
| 489 |
/// break; |
| 490 |
/// } |
| 491 |
/// } |
| 492 |
/// }); |
| 493 |
/// |
| 494 |
/// sleep(Duration::from_millis(100)).await; |
| 495 |
/// tx.send("world")?; |
| 496 |
/// # Ok(()) |
| 497 |
/// # } |
| 498 |
/// ``` |
| 499 |
/// |
| 500 |
/// [`Sender`]: struct@Sender |
| 501 |
/// [`Receiver`]: struct@Receiver |
| 502 |
pub fn channel<T>(init: T) -> (Sender<T>, Receiver<T>) { |
| 503 |
let shared = Arc::new(Shared { |
| 504 |
value: RwLock::new(init), |
| 505 |
state: AtomicState::new(), |
| 506 |
ref_count_rx: AtomicUsize::new(1), |
| 507 |
ref_count_tx: AtomicUsize::new(1), |
| 508 |
notify_rx: big_notify::BigNotify::new(), |
| 509 |
notify_tx: Notify::new(), |
| 510 |
}); |
| 511 |
|
| 512 |
let tx = Sender { |
| 513 |
shared: shared.clone(), |
| 514 |
}; |
| 515 |
|
| 516 |
let rx = Receiver { |
| 517 |
shared, |
| 518 |
version: Version::INITIAL, |
| 519 |
}; |
| 520 |
|
| 521 |
(tx, rx) |
| 522 |
} |
| 523 |
|
| 524 |
impl<T> Receiver<T> { |
| 525 |
fn from_shared(version: Version, shared: Arc<Shared<T>>) -> Self { |
| 526 |
// No synchronization necessary as this is only used as a counter and |
| 527 |
// not memory access. |
| 528 |
shared.ref_count_rx.fetch_add(1, Relaxed); |
| 529 |
|
| 530 |
Self { shared, version } |
| 531 |
} |
| 532 |
|
| 533 |
/// Returns a reference to the most recently sent value. |
| 534 |
/// |
| 535 |
/// This method does not mark the returned value as seen, so future calls to |
| 536 |
/// [`changed`] may return immediately even if you have already seen the |
| 537 |
/// value with a call to `borrow`. |
| 538 |
/// |
| 539 |
/// Outstanding borrows hold a read lock on the inner value. This means that |
| 540 |
/// long-lived borrows could cause the producer half to block. It is recommended |
| 541 |
/// to keep the borrow as short-lived as possible. Additionally, if you are |
| 542 |
/// running in an environment that allows `!Send` futures, you must ensure that |
| 543 |
/// the returned `Ref` type is never held alive across an `.await` point, |
| 544 |
/// otherwise, it can lead to a deadlock. |
| 545 |
/// |
| 546 |
/// The priority policy of the lock is dependent on the underlying lock |
| 547 |
/// implementation, and this type does not guarantee that any particular policy |
| 548 |
/// will be used. In particular, a producer which is waiting to acquire the lock |
| 549 |
/// in `send` might or might not block concurrent calls to `borrow`, e.g.: |
| 550 |
/// |
| 551 |
/// <details><summary>Potential deadlock example</summary> |
| 552 |
/// |
| 553 |
/// ```text |
| 554 |
/// // Task 1 (on thread A) | // Task 2 (on thread B) |
| 555 |
/// let _ref1 = rx.borrow(); | |
| 556 |
/// | // will block |
| 557 |
/// | let _ = tx.send(()); |
| 558 |
/// // may deadlock | |
| 559 |
/// let _ref2 = rx.borrow(); | |
| 560 |
/// ``` |
| 561 |
/// </details> |
| 562 |
/// |
| 563 |
/// For more information on when to use this method versus |
| 564 |
/// [`borrow_and_update`], see [here](self#borrow_and_update-versus-borrow). |
| 565 |
/// |
| 566 |
/// [`changed`]: Receiver::changed |
| 567 |
/// [`borrow_and_update`]: Receiver::borrow_and_update |
| 568 |
/// |
| 569 |
/// # Examples |
| 570 |
/// |
| 571 |
/// ``` |
| 572 |
/// use tokio::sync::watch; |
| 573 |
/// |
| 574 |
/// let (_, rx) = watch::channel("hello"); |
| 575 |
/// assert_eq!(*rx.borrow(), "hello"); |
| 576 |
/// ``` |
| 577 |
pub fn borrow(&self) -> Ref<'_, T> { |
| 578 |
let inner = self.shared.value.read().unwrap(); |
| 579 |
|
| 580 |
// After obtaining a read-lock no concurrent writes could occur |
| 581 |
// and the loaded version matches that of the borrowed reference. |
| 582 |
let new_version = self.shared.state.load().version(); |
| 583 |
let has_changed = self.version != new_version; |
| 584 |
|
| 585 |
Ref { inner, has_changed } |
| 586 |
} |
| 587 |
|
| 588 |
/// Returns a reference to the most recently sent value and marks that value |
| 589 |
/// as seen. |
| 590 |
/// |
| 591 |
/// This method marks the current value as seen. Subsequent calls to [`changed`] |
| 592 |
/// will not return immediately until the [`Sender`] has modified the shared |
| 593 |
/// value again. |
| 594 |
/// |
| 595 |
/// Outstanding borrows hold a read lock on the inner value. This means that |
| 596 |
/// long-lived borrows could cause the producer half to block. It is recommended |
| 597 |
/// to keep the borrow as short-lived as possible. Additionally, if you are |
| 598 |
/// running in an environment that allows `!Send` futures, you must ensure that |
| 599 |
/// the returned `Ref` type is never held alive across an `.await` point, |
| 600 |
/// otherwise, it can lead to a deadlock. |
| 601 |
/// |
| 602 |
/// The priority policy of the lock is dependent on the underlying lock |
| 603 |
/// implementation, and this type does not guarantee that any particular policy |
| 604 |
/// will be used. In particular, a producer which is waiting to acquire the lock |
| 605 |
/// in `send` might or might not block concurrent calls to `borrow`, e.g.: |
| 606 |
/// |
| 607 |
/// <details><summary>Potential deadlock example</summary> |
| 608 |
/// |
| 609 |
/// ```text |
| 610 |
/// // Task 1 (on thread A) | // Task 2 (on thread B) |
| 611 |
/// let _ref1 = rx1.borrow_and_update(); | |
| 612 |
/// | // will block |
| 613 |
/// | let _ = tx.send(()); |
| 614 |
/// // may deadlock | |
| 615 |
/// let _ref2 = rx2.borrow_and_update(); | |
| 616 |
/// ``` |
| 617 |
/// </details> |
| 618 |
/// |
| 619 |
/// For more information on when to use this method versus [`borrow`], see |
| 620 |
/// [here](self#borrow_and_update-versus-borrow). |
| 621 |
/// |
| 622 |
/// [`changed`]: Receiver::changed |
| 623 |
/// [`borrow`]: Receiver::borrow |
| 624 |
pub fn borrow_and_update(&mut self) -> Ref<'_, T> { |
| 625 |
let inner = self.shared.value.read().unwrap(); |
| 626 |
|
| 627 |
// After obtaining a read-lock no concurrent writes could occur |
| 628 |
// and the loaded version matches that of the borrowed reference. |
| 629 |
let new_version = self.shared.state.load().version(); |
| 630 |
let has_changed = self.version != new_version; |
| 631 |
|
| 632 |
// Mark the shared value as seen by updating the version |
| 633 |
self.version = new_version; |
| 634 |
|
| 635 |
Ref { inner, has_changed } |
| 636 |
} |
| 637 |
|
| 638 |
/// Checks if this channel contains a message that this receiver has not yet |
| 639 |
/// seen. The new value is not marked as seen. |
| 640 |
/// |
| 641 |
/// Although this method is called `has_changed`, it does not check new |
| 642 |
/// messages for equality, so this call will return true even if the new |
| 643 |
/// message is equal to the old message. |
| 644 |
/// |
| 645 |
/// Returns an error if the channel has been closed. |
| 646 |
/// # Examples |
| 647 |
/// |
| 648 |
/// ``` |
| 649 |
/// use tokio::sync::watch; |
| 650 |
/// |
| 651 |
/// #[tokio::main] |
| 652 |
/// async fn main() { |
| 653 |
/// let (tx, mut rx) = watch::channel("hello"); |
| 654 |
/// |
| 655 |
/// tx.send("goodbye").unwrap(); |
| 656 |
/// |
| 657 |
/// assert!(rx.has_changed().unwrap()); |
| 658 |
/// assert_eq!(*rx.borrow_and_update(), "goodbye"); |
| 659 |
/// |
| 660 |
/// // The value has been marked as seen |
| 661 |
/// assert!(!rx.has_changed().unwrap()); |
| 662 |
/// |
| 663 |
/// drop(tx); |
| 664 |
/// // The `tx` handle has been dropped |
| 665 |
/// assert!(rx.has_changed().is_err()); |
| 666 |
/// } |
| 667 |
/// ``` |
| 668 |
pub fn has_changed(&self) -> Result<bool, error::RecvError> { |
| 669 |
// Load the version from the state |
| 670 |
let state = self.shared.state.load(); |
| 671 |
if state.is_closed() { |
| 672 |
// The sender has dropped. |
| 673 |
return Err(error::RecvError(())); |
| 674 |
} |
| 675 |
let new_version = state.version(); |
| 676 |
|
| 677 |
Ok(self.version != new_version) |
| 678 |
} |
| 679 |
|
| 680 |
/// Marks the state as changed. |
| 681 |
/// |
| 682 |
/// After invoking this method [`has_changed()`](Self::has_changed) |
| 683 |
/// returns `true` and [`changed()`](Self::changed) returns |
| 684 |
/// immediately, regardless of whether a new value has been sent. |
| 685 |
/// |
| 686 |
/// This is useful for triggering an initial change notification after |
| 687 |
/// subscribing to synchronize new receivers. |
| 688 |
pub fn mark_changed(&mut self) { |
| 689 |
self.version.decrement(); |
| 690 |
} |
| 691 |
|
| 692 |
/// Marks the state as unchanged. |
| 693 |
/// |
| 694 |
/// The current value will be considered seen by the receiver. |
| 695 |
/// |
| 696 |
/// This is useful if you are not interested in the current value |
| 697 |
/// visible in the receiver. |
| 698 |
pub fn mark_unchanged(&mut self) { |
| 699 |
let current_version = self.shared.state.load().version(); |
| 700 |
self.version = current_version; |
| 701 |
} |
| 702 |
|
| 703 |
/// Waits for a change notification, then marks the newest value as seen. |
| 704 |
/// |
| 705 |
/// If the newest value in the channel has not yet been marked seen when |
| 706 |
/// this method is called, the method marks that value seen and returns |
| 707 |
/// immediately. If the newest value has already been marked seen, then the |
| 708 |
/// method sleeps until a new message is sent by the [`Sender`] connected to |
| 709 |
/// this `Receiver`, or until the [`Sender`] is dropped. |
| 710 |
/// |
| 711 |
/// This method returns an error if and only if the [`Sender`] is dropped. |
| 712 |
/// |
| 713 |
/// For more information, see |
| 714 |
/// [*Change notifications*](self#change-notifications) in the module-level documentation. |
| 715 |
/// |
| 716 |
/// # Cancel safety |
| 717 |
/// |
| 718 |
/// This method is cancel safe. If you use it as the event in a |
| 719 |
/// [`tokio::select!`](crate::select) statement and some other branch |
| 720 |
/// completes first, then it is guaranteed that no values have been marked |
| 721 |
/// seen by this call to `changed`. |
| 722 |
/// |
| 723 |
/// [`Sender`]: struct@Sender |
| 724 |
/// |
| 725 |
/// # Examples |
| 726 |
/// |
| 727 |
/// ``` |
| 728 |
/// use tokio::sync::watch; |
| 729 |
/// |
| 730 |
/// #[tokio::main] |
| 731 |
/// async fn main() { |
| 732 |
/// let (tx, mut rx) = watch::channel("hello"); |
| 733 |
/// |
| 734 |
/// tokio::spawn(async move { |
| 735 |
/// tx.send("goodbye").unwrap(); |
| 736 |
/// }); |
| 737 |
/// |
| 738 |
/// assert!(rx.changed().await.is_ok()); |
| 739 |
/// assert_eq!(*rx.borrow_and_update(), "goodbye"); |
| 740 |
/// |
| 741 |
/// // The `tx` handle has been dropped |
| 742 |
/// assert!(rx.changed().await.is_err()); |
| 743 |
/// } |
| 744 |
/// ``` |
| 745 |
pub async fn changed(&mut self) -> Result<(), error::RecvError> { |
| 746 |
changed_impl(&self.shared, &mut self.version).await |
| 747 |
} |
| 748 |
|
| 749 |
/// Waits for a value that satisfies the provided condition. |
| 750 |
/// |
| 751 |
/// This method will call the provided closure whenever something is sent on |
| 752 |
/// the channel. Once the closure returns `true`, this method will return a |
| 753 |
/// reference to the value that was passed to the closure. |
| 754 |
/// |
| 755 |
/// Before `wait_for` starts waiting for changes, it will call the closure |
| 756 |
/// on the current value. If the closure returns `true` when given the |
| 757 |
/// current value, then `wait_for` will immediately return a reference to |
| 758 |
/// the current value. This is the case even if the current value is already |
| 759 |
/// considered seen. |
| 760 |
/// |
| 761 |
/// The watch channel only keeps track of the most recent value, so if |
| 762 |
/// several messages are sent faster than `wait_for` is able to call the |
| 763 |
/// closure, then it may skip some updates. Whenever the closure is called, |
| 764 |
/// it will be called with the most recent value. |
| 765 |
/// |
| 766 |
/// When this function returns, the value that was passed to the closure |
| 767 |
/// when it returned `true` will be considered seen. |
| 768 |
/// |
| 769 |
/// If the channel is closed, then `wait_for` will return a `RecvError`. |
| 770 |
/// Once this happens, no more messages can ever be sent on the channel. |
| 771 |
/// When an error is returned, it is guaranteed that the closure has been |
| 772 |
/// called on the last value, and that it returned `false` for that value. |
| 773 |
/// (If the closure returned `true`, then the last value would have been |
| 774 |
/// returned instead of the error.) |
| 775 |
/// |
| 776 |
/// Like the `borrow` method, the returned borrow holds a read lock on the |
| 777 |
/// inner value. This means that long-lived borrows could cause the producer |
| 778 |
/// half to block. It is recommended to keep the borrow as short-lived as |
| 779 |
/// possible. See the documentation of `borrow` for more information on |
| 780 |
/// this. |
| 781 |
/// |
| 782 |
/// [`Receiver::changed()`]: crate::sync::watch::Receiver::changed |
| 783 |
/// |
| 784 |
/// # Examples |
| 785 |
/// |
| 786 |
/// ``` |
| 787 |
/// use tokio::sync::watch; |
| 788 |
/// |
| 789 |
/// #[tokio::main] |
| 790 |
/// |
| 791 |
/// async fn main() { |
| 792 |
/// let (tx, _rx) = watch::channel("hello"); |
| 793 |
/// |
| 794 |
/// tx.send("goodbye").unwrap(); |
| 795 |
/// |
| 796 |
/// // here we subscribe to a second receiver |
| 797 |
/// // now in case of using `changed` we would have |
| 798 |
/// // to first check the current value and then wait |
| 799 |
/// // for changes or else `changed` would hang. |
| 800 |
/// let mut rx2 = tx.subscribe(); |
| 801 |
/// |
| 802 |
/// // in place of changed we have use `wait_for` |
| 803 |
/// // which would automatically check the current value |
| 804 |
/// // and wait for changes until the closure returns true. |
| 805 |
/// assert!(rx2.wait_for(|val| *val == "goodbye").await.is_ok()); |
| 806 |
/// assert_eq!(*rx2.borrow(), "goodbye"); |
| 807 |
/// } |
| 808 |
/// ``` |
| 809 |
pub async fn wait_for( |
| 810 |
&mut self, |
| 811 |
mut f: impl FnMut(&T) -> bool, |
| 812 |
) -> Result<Ref<'_, T>, error::RecvError> { |
| 813 |
let mut closed = false; |
| 814 |
loop { |
| 815 |
{ |
| 816 |
let inner = self.shared.value.read().unwrap(); |
| 817 |
|
| 818 |
let new_version = self.shared.state.load().version(); |
| 819 |
let has_changed = self.version != new_version; |
| 820 |
self.version = new_version; |
| 821 |
|
| 822 |
if !closed || has_changed { |
| 823 |
let result = panic::catch_unwind(panic::AssertUnwindSafe(|| f(&inner))); |
| 824 |
match result { |
| 825 |
Ok(true) => { |
| 826 |
return Ok(Ref { inner, has_changed }); |
| 827 |
} |
| 828 |
Ok(false) => { |
| 829 |
// Skip the value. |
| 830 |
} |
| 831 |
Err(panicked) => { |
| 832 |
// Drop the read-lock to avoid poisoning it. |
| 833 |
drop(inner); |
| 834 |
// Forward the panic to the caller. |
| 835 |
panic::resume_unwind(panicked); |
| 836 |
// Unreachable |
| 837 |
} |
| 838 |
}; |
| 839 |
} |
| 840 |
} |
| 841 |
|
| 842 |
if closed { |
| 843 |
return Err(error::RecvError(())); |
| 844 |
} |
| 845 |
|
| 846 |
// Wait for the value to change. |
| 847 |
closed = changed_impl(&self.shared, &mut self.version).await.is_err(); |
| 848 |
} |
| 849 |
} |
| 850 |
|
| 851 |
/// Returns `true` if receivers belong to the same channel. |
| 852 |
/// |
| 853 |
/// # Examples |
| 854 |
/// |
| 855 |
/// ``` |
| 856 |
/// let (tx, rx) = tokio::sync::watch::channel(true); |
| 857 |
/// let rx2 = rx.clone(); |
| 858 |
/// assert!(rx.same_channel(&rx2)); |
| 859 |
/// |
| 860 |
/// let (tx3, rx3) = tokio::sync::watch::channel(true); |
| 861 |
/// assert!(!rx3.same_channel(&rx2)); |
| 862 |
/// ``` |
| 863 |
pub fn same_channel(&self, other: &Self) -> bool { |
| 864 |
Arc::ptr_eq(&self.shared, &other.shared) |
| 865 |
} |
| 866 |
|
| 867 |
cfg_process_driver! { |
| 868 |
pub(crate) fn try_has_changed(&mut self) -> Option<Result<(), error::RecvError>> { |
| 869 |
maybe_changed(&self.shared, &mut self.version) |
| 870 |
} |
| 871 |
} |
| 872 |
} |
| 873 |
|
| 874 |
fn maybe_changed<T>( |
| 875 |
shared: &Shared<T>, |
| 876 |
version: &mut Version, |
| 877 |
) -> Option<Result<(), error::RecvError>> { |
| 878 |
// Load the version from the state |
| 879 |
let state = shared.state.load(); |
| 880 |
let new_version = state.version(); |
| 881 |
|
| 882 |
if *version != new_version { |
| 883 |
// Observe the new version and return |
| 884 |
*version = new_version; |
| 885 |
return Some(Ok(())); |
| 886 |
} |
| 887 |
|
| 888 |
if state.is_closed() { |
| 889 |
// The sender has been dropped. |
| 890 |
return Some(Err(error::RecvError(()))); |
| 891 |
} |
| 892 |
|
| 893 |
None |
| 894 |
} |
| 895 |
|
| 896 |
async fn changed_impl<T>( |
| 897 |
shared: &Shared<T>, |
| 898 |
version: &mut Version, |
| 899 |
) -> Result<(), error::RecvError> { |
| 900 |
crate::trace::async_trace_leaf().await; |
| 901 |
|
| 902 |
loop { |
| 903 |
// In order to avoid a race condition, we first request a notification, |
| 904 |
// **then** check the current value's version. If a new version exists, |
| 905 |
// the notification request is dropped. |
| 906 |
let notified = shared.notify_rx.notified(); |
| 907 |
|
| 908 |
if let Some(ret) = maybe_changed(shared, version) { |
| 909 |
return ret; |
| 910 |
} |
| 911 |
|
| 912 |
notified.await; |
| 913 |
// loop around again in case the wake-up was spurious |
| 914 |
} |
| 915 |
} |
| 916 |
|
| 917 |
impl<T> Clone for Receiver<T> { |
| 918 |
fn clone(&self) -> Self { |
| 919 |
let version = self.version; |
| 920 |
let shared = self.shared.clone(); |
| 921 |
|
| 922 |
Self::from_shared(version, shared) |
| 923 |
} |
| 924 |
} |
| 925 |
|
| 926 |
impl<T> Drop for Receiver<T> { |
| 927 |
fn drop(&mut self) { |
| 928 |
// No synchronization necessary as this is only used as a counter and |
| 929 |
// not memory access. |
| 930 |
if 1 == self.shared.ref_count_rx.fetch_sub(1, Relaxed) { |
| 931 |
// This is the last `Receiver` handle, tasks waiting on `Sender::closed()` |
| 932 |
self.shared.notify_tx.notify_waiters(); |
| 933 |
} |
| 934 |
} |
| 935 |
} |
| 936 |
|
| 937 |
impl<T> Sender<T> { |
| 938 |
/// Creates the sending-half of the [`watch`] channel. |
| 939 |
/// |
| 940 |
/// See documentation of [`watch::channel`] for errors when calling this function. |
| 941 |
/// Beware that attempting to send a value when there are no receivers will |
| 942 |
/// return an error. |
| 943 |
/// |
| 944 |
/// [`watch`]: crate::sync::watch |
| 945 |
/// [`watch::channel`]: crate::sync::watch |
| 946 |
/// |
| 947 |
/// # Examples |
| 948 |
/// ``` |
| 949 |
/// let sender = tokio::sync::watch::Sender::new(0u8); |
| 950 |
/// assert!(sender.send(3).is_err()); |
| 951 |
/// let _rec = sender.subscribe(); |
| 952 |
/// assert!(sender.send(4).is_ok()); |
| 953 |
/// ``` |
| 954 |
pub fn new(init: T) -> Self { |
| 955 |
let (tx, _) = channel(init); |
| 956 |
tx |
| 957 |
} |
| 958 |
|
| 959 |
/// Sends a new value via the channel, notifying all receivers. |
| 960 |
/// |
| 961 |
/// This method fails if the channel is closed, which is the case when |
| 962 |
/// every receiver has been dropped. It is possible to reopen the channel |
| 963 |
/// using the [`subscribe`] method. However, when `send` fails, the value |
| 964 |
/// isn't made available for future receivers (but returned with the |
| 965 |
/// [`SendError`]). |
| 966 |
/// |
| 967 |
/// To always make a new value available for future receivers, even if no |
| 968 |
/// receiver currently exists, one of the other send methods |
| 969 |
/// ([`send_if_modified`], [`send_modify`], or [`send_replace`]) can be |
| 970 |
/// used instead. |
| 971 |
/// |
| 972 |
/// [`subscribe`]: Sender::subscribe |
| 973 |
/// [`SendError`]: error::SendError |
| 974 |
/// [`send_if_modified`]: Sender::send_if_modified |
| 975 |
/// [`send_modify`]: Sender::send_modify |
| 976 |
/// [`send_replace`]: Sender::send_replace |
| 977 |
pub fn send(&self, value: T) -> Result<(), error::SendError<T>> { |
| 978 |
// This is pretty much only useful as a hint anyway, so synchronization isn't critical. |
| 979 |
if 0 == self.receiver_count() { |
| 980 |
return Err(error::SendError(value)); |
| 981 |
} |
| 982 |
|
| 983 |
self.send_replace(value); |
| 984 |
Ok(()) |
| 985 |
} |
| 986 |
|
| 987 |
/// Modifies the watched value **unconditionally** in-place, |
| 988 |
/// notifying all receivers. |
| 989 |
/// |
| 990 |
/// This can be useful for modifying the watched value, without |
| 991 |
/// having to allocate a new instance. Additionally, this |
| 992 |
/// method permits sending values even when there are no receivers. |
| 993 |
/// |
| 994 |
/// Prefer to use the more versatile function [`Self::send_if_modified()`] |
| 995 |
/// if the value is only modified conditionally during the mutable borrow |
| 996 |
/// to prevent unneeded change notifications for unmodified values. |
| 997 |
/// |
| 998 |
/// # Panics |
| 999 |
/// |
| 1000 |
/// This function panics when the invocation of the `modify` closure panics. |
| 1001 |
/// No receivers are notified when panicking. All changes of the watched |
| 1002 |
/// value applied by the closure before panicking will be visible in |
| 1003 |
/// subsequent calls to `borrow`. |
| 1004 |
/// |
| 1005 |
/// # Examples |
| 1006 |
/// |
| 1007 |
/// ``` |
| 1008 |
/// use tokio::sync::watch; |
| 1009 |
/// |
| 1010 |
/// struct State { |
| 1011 |
/// counter: usize, |
| 1012 |
/// } |
| 1013 |
/// let (state_tx, state_rx) = watch::channel(State { counter: 0 }); |
| 1014 |
/// state_tx.send_modify(|state| state.counter += 1); |
| 1015 |
/// assert_eq!(state_rx.borrow().counter, 1); |
| 1016 |
/// ``` |
| 1017 |
pub fn send_modify<F>(&self, modify: F) |
| 1018 |
where |
| 1019 |
F: FnOnce(&mut T), |
| 1020 |
{ |
| 1021 |
self.send_if_modified(|value| { |
| 1022 |
modify(value); |
| 1023 |
true |
| 1024 |
}); |
| 1025 |
} |
| 1026 |
|
| 1027 |
/// Modifies the watched value **conditionally** in-place, |
| 1028 |
/// notifying all receivers only if modified. |
| 1029 |
/// |
| 1030 |
/// This can be useful for modifying the watched value, without |
| 1031 |
/// having to allocate a new instance. Additionally, this |
| 1032 |
/// method permits sending values even when there are no receivers. |
| 1033 |
/// |
| 1034 |
/// The `modify` closure must return `true` if the value has actually |
| 1035 |
/// been modified during the mutable borrow. It should only return `false` |
| 1036 |
/// if the value is guaranteed to be unmodified despite the mutable |
| 1037 |
/// borrow. |
| 1038 |
/// |
| 1039 |
/// Receivers are only notified if the closure returned `true`. If the |
| 1040 |
/// closure has modified the value but returned `false` this results |
| 1041 |
/// in a *silent modification*, i.e. the modified value will be visible |
| 1042 |
/// in subsequent calls to `borrow`, but receivers will not receive |
| 1043 |
/// a change notification. |
| 1044 |
/// |
| 1045 |
/// Returns the result of the closure, i.e. `true` if the value has |
| 1046 |
/// been modified and `false` otherwise. |
| 1047 |
/// |
| 1048 |
/// # Panics |
| 1049 |
/// |
| 1050 |
/// This function panics when the invocation of the `modify` closure panics. |
| 1051 |
/// No receivers are notified when panicking. All changes of the watched |
| 1052 |
/// value applied by the closure before panicking will be visible in |
| 1053 |
/// subsequent calls to `borrow`. |
| 1054 |
/// |
| 1055 |
/// # Examples |
| 1056 |
/// |
| 1057 |
/// ``` |
| 1058 |
/// use tokio::sync::watch; |
| 1059 |
/// |
| 1060 |
/// struct State { |
| 1061 |
/// counter: usize, |
| 1062 |
/// } |
| 1063 |
/// let (state_tx, mut state_rx) = watch::channel(State { counter: 1 }); |
| 1064 |
/// let inc_counter_if_odd = |state: &mut State| { |
| 1065 |
/// if state.counter % 2 == 1 { |
| 1066 |
/// state.counter += 1; |
| 1067 |
/// return true; |
| 1068 |
/// } |
| 1069 |
/// false |
| 1070 |
/// }; |
| 1071 |
/// |
| 1072 |
/// assert_eq!(state_rx.borrow().counter, 1); |
| 1073 |
/// |
| 1074 |
/// assert!(!state_rx.has_changed().unwrap()); |
| 1075 |
/// assert!(state_tx.send_if_modified(inc_counter_if_odd)); |
| 1076 |
/// assert!(state_rx.has_changed().unwrap()); |
| 1077 |
/// assert_eq!(state_rx.borrow_and_update().counter, 2); |
| 1078 |
/// |
| 1079 |
/// assert!(!state_rx.has_changed().unwrap()); |
| 1080 |
/// assert!(!state_tx.send_if_modified(inc_counter_if_odd)); |
| 1081 |
/// assert!(!state_rx.has_changed().unwrap()); |
| 1082 |
/// assert_eq!(state_rx.borrow_and_update().counter, 2); |
| 1083 |
/// ``` |
| 1084 |
pub fn send_if_modified<F>(&self, modify: F) -> bool |
| 1085 |
where |
| 1086 |
F: FnOnce(&mut T) -> bool, |
| 1087 |
{ |
| 1088 |
{ |
| 1089 |
// Acquire the write lock and update the value. |
| 1090 |
let mut lock = self.shared.value.write().unwrap(); |
| 1091 |
|
| 1092 |
// Update the value and catch possible panic inside func. |
| 1093 |
let result = panic::catch_unwind(panic::AssertUnwindSafe(|| modify(&mut lock))); |
| 1094 |
match result { |
| 1095 |
Ok(modified) => { |
| 1096 |
if !modified { |
| 1097 |
// Abort, i.e. don't notify receivers if unmodified |
| 1098 |
return false; |
| 1099 |
} |
| 1100 |
// Continue if modified |
| 1101 |
} |
| 1102 |
Err(panicked) => { |
| 1103 |
// Drop the lock to avoid poisoning it. |
| 1104 |
drop(lock); |
| 1105 |
// Forward the panic to the caller. |
| 1106 |
panic::resume_unwind(panicked); |
| 1107 |
// Unreachable |
| 1108 |
} |
| 1109 |
}; |
| 1110 |
|
| 1111 |
self.shared.state.increment_version_while_locked(); |
| 1112 |
|
| 1113 |
// Release the write lock. |
| 1114 |
// |
| 1115 |
// Incrementing the version counter while holding the lock ensures |
| 1116 |
// that receivers are able to figure out the version number of the |
| 1117 |
// value they are currently looking at. |
| 1118 |
drop(lock); |
| 1119 |
} |
| 1120 |
|
| 1121 |
self.shared.notify_rx.notify_waiters(); |
| 1122 |
|
| 1123 |
true |
| 1124 |
} |
| 1125 |
|
| 1126 |
/// Sends a new value via the channel, notifying all receivers and returning |
| 1127 |
/// the previous value in the channel. |
| 1128 |
/// |
| 1129 |
/// This can be useful for reusing the buffers inside a watched value. |
| 1130 |
/// Additionally, this method permits sending values even when there are no |
| 1131 |
/// receivers. |
| 1132 |
/// |
| 1133 |
/// # Examples |
| 1134 |
/// |
| 1135 |
/// ``` |
| 1136 |
/// use tokio::sync::watch; |
| 1137 |
/// |
| 1138 |
/// let (tx, _rx) = watch::channel(1); |
| 1139 |
/// assert_eq!(tx.send_replace(2), 1); |
| 1140 |
/// assert_eq!(tx.send_replace(3), 2); |
| 1141 |
/// ``` |
| 1142 |
pub fn send_replace(&self, mut value: T) -> T { |
| 1143 |
// swap old watched value with the new one |
| 1144 |
self.send_modify(|old| mem::swap(old, &mut value)); |
| 1145 |
|
| 1146 |
value |
| 1147 |
} |
| 1148 |
|
| 1149 |
/// Returns a reference to the most recently sent value |
| 1150 |
/// |
| 1151 |
/// Outstanding borrows hold a read lock on the inner value. This means that |
| 1152 |
/// long-lived borrows could cause the producer half to block. It is recommended |
| 1153 |
/// to keep the borrow as short-lived as possible. Additionally, if you are |
| 1154 |
/// running in an environment that allows `!Send` futures, you must ensure that |
| 1155 |
/// the returned `Ref` type is never held alive across an `.await` point, |
| 1156 |
/// otherwise, it can lead to a deadlock. |
| 1157 |
/// |
| 1158 |
/// # Examples |
| 1159 |
/// |
| 1160 |
/// ``` |
| 1161 |
/// use tokio::sync::watch; |
| 1162 |
/// |
| 1163 |
/// let (tx, _) = watch::channel("hello"); |
| 1164 |
/// assert_eq!(*tx.borrow(), "hello"); |
| 1165 |
/// ``` |
| 1166 |
pub fn borrow(&self) -> Ref<'_, T> { |
| 1167 |
let inner = self.shared.value.read().unwrap(); |
| 1168 |
|
| 1169 |
// The sender/producer always sees the current version |
| 1170 |
let has_changed = false; |
| 1171 |
|
| 1172 |
Ref { inner, has_changed } |
| 1173 |
} |
| 1174 |
|
| 1175 |
/// Checks if the channel has been closed. This happens when all receivers |
| 1176 |
/// have dropped. |
| 1177 |
/// |
| 1178 |
/// # Examples |
| 1179 |
/// |
| 1180 |
/// ``` |
| 1181 |
/// let (tx, rx) = tokio::sync::watch::channel(()); |
| 1182 |
/// assert!(!tx.is_closed()); |
| 1183 |
/// |
| 1184 |
/// drop(rx); |
| 1185 |
/// assert!(tx.is_closed()); |
| 1186 |
/// ``` |
| 1187 |
pub fn is_closed(&self) -> bool { |
| 1188 |
self.receiver_count() == 0 |
| 1189 |
} |
| 1190 |
|
| 1191 |
/// Completes when all receivers have dropped. |
| 1192 |
/// |
| 1193 |
/// This allows the producer to get notified when interest in the produced |
| 1194 |
/// values is canceled and immediately stop doing work. Once a channel is |
| 1195 |
/// closed, the only way to reopen it is to call [`Sender::subscribe`] to |
| 1196 |
/// get a new receiver. |
| 1197 |
/// |
| 1198 |
/// If the channel becomes closed for a brief amount of time (e.g., the last |
| 1199 |
/// receiver is dropped and then `subscribe` is called), then this call to |
| 1200 |
/// `closed` might return, but it is also possible that it does not "notice" |
| 1201 |
/// that the channel was closed for a brief amount of time. |
| 1202 |
/// |
| 1203 |
/// # Cancel safety |
| 1204 |
/// |
| 1205 |
/// This method is cancel safe. |
| 1206 |
/// |
| 1207 |
/// # Examples |
| 1208 |
/// |
| 1209 |
/// ``` |
| 1210 |
/// use tokio::sync::watch; |
| 1211 |
/// |
| 1212 |
/// #[tokio::main] |
| 1213 |
/// async fn main() { |
| 1214 |
/// let (tx, rx) = watch::channel("hello"); |
| 1215 |
/// |
| 1216 |
/// tokio::spawn(async move { |
| 1217 |
/// // use `rx` |
| 1218 |
/// drop(rx); |
| 1219 |
/// }); |
| 1220 |
/// |
| 1221 |
/// // Waits for `rx` to drop |
| 1222 |
/// tx.closed().await; |
| 1223 |
/// println!("the `rx` handles dropped") |
| 1224 |
/// } |
| 1225 |
/// ``` |
| 1226 |
pub async fn closed(&self) { |
| 1227 |
crate::trace::async_trace_leaf().await; |
| 1228 |
|
| 1229 |
while self.receiver_count() > 0 { |
| 1230 |
let notified = self.shared.notify_tx.notified(); |
| 1231 |
|
| 1232 |
if self.receiver_count() == 0 { |
| 1233 |
return; |
| 1234 |
} |
| 1235 |
|
| 1236 |
notified.await; |
| 1237 |
// The channel could have been reopened in the meantime by calling |
| 1238 |
// `subscribe`, so we loop again. |
| 1239 |
} |
| 1240 |
} |
| 1241 |
|
| 1242 |
/// Creates a new [`Receiver`] connected to this `Sender`. |
| 1243 |
/// |
| 1244 |
/// All messages sent before this call to `subscribe` are initially marked |
| 1245 |
/// as seen by the new `Receiver`. |
| 1246 |
/// |
| 1247 |
/// This method can be called even if there are no other receivers. In this |
| 1248 |
/// case, the channel is reopened. |
| 1249 |
/// |
| 1250 |
/// # Examples |
| 1251 |
/// |
| 1252 |
/// The new channel will receive messages sent on this `Sender`. |
| 1253 |
/// |
| 1254 |
/// ``` |
| 1255 |
/// use tokio::sync::watch; |
| 1256 |
/// |
| 1257 |
/// #[tokio::main] |
| 1258 |
/// async fn main() { |
| 1259 |
/// let (tx, _rx) = watch::channel(0u64); |
| 1260 |
/// |
| 1261 |
/// tx.send(5).unwrap(); |
| 1262 |
/// |
| 1263 |
/// let rx = tx.subscribe(); |
| 1264 |
/// assert_eq!(5, *rx.borrow()); |
| 1265 |
/// |
| 1266 |
/// tx.send(10).unwrap(); |
| 1267 |
/// assert_eq!(10, *rx.borrow()); |
| 1268 |
/// } |
| 1269 |
/// ``` |
| 1270 |
/// |
| 1271 |
/// The most recent message is considered seen by the channel, so this test |
| 1272 |
/// is guaranteed to pass. |
| 1273 |
/// |
| 1274 |
/// ``` |
| 1275 |
/// use tokio::sync::watch; |
| 1276 |
/// use tokio::time::Duration; |
| 1277 |
/// |
| 1278 |
/// #[tokio::main] |
| 1279 |
/// async fn main() { |
| 1280 |
/// let (tx, _rx) = watch::channel(0u64); |
| 1281 |
/// tx.send(5).unwrap(); |
| 1282 |
/// let mut rx = tx.subscribe(); |
| 1283 |
/// |
| 1284 |
/// tokio::spawn(async move { |
| 1285 |
/// // by spawning and sleeping, the message is sent after `main` |
| 1286 |
/// // hits the call to `changed`. |
| 1287 |
/// # if false { |
| 1288 |
/// tokio::time::sleep(Duration::from_millis(10)).await; |
| 1289 |
/// # } |
| 1290 |
/// tx.send(100).unwrap(); |
| 1291 |
/// }); |
| 1292 |
/// |
| 1293 |
/// rx.changed().await.unwrap(); |
| 1294 |
/// assert_eq!(100, *rx.borrow()); |
| 1295 |
/// } |
| 1296 |
/// ``` |
| 1297 |
pub fn subscribe(&self) -> Receiver<T> { |
| 1298 |
let shared = self.shared.clone(); |
| 1299 |
let version = shared.state.load().version(); |
| 1300 |
|
| 1301 |
// The CLOSED bit in the state tracks only whether the sender is |
| 1302 |
// dropped, so we do not need to unset it if this reopens the channel. |
| 1303 |
Receiver::from_shared(version, shared) |
| 1304 |
} |
| 1305 |
|
| 1306 |
/// Returns the number of receivers that currently exist. |
| 1307 |
/// |
| 1308 |
/// # Examples |
| 1309 |
/// |
| 1310 |
/// ``` |
| 1311 |
/// use tokio::sync::watch; |
| 1312 |
/// |
| 1313 |
/// #[tokio::main] |
| 1314 |
/// async fn main() { |
| 1315 |
/// let (tx, rx1) = watch::channel("hello"); |
| 1316 |
/// |
| 1317 |
/// assert_eq!(1, tx.receiver_count()); |
| 1318 |
/// |
| 1319 |
/// let mut _rx2 = rx1.clone(); |
| 1320 |
/// |
| 1321 |
/// assert_eq!(2, tx.receiver_count()); |
| 1322 |
/// } |
| 1323 |
/// ``` |
| 1324 |
pub fn receiver_count(&self) -> usize { |
| 1325 |
self.shared.ref_count_rx.load(Relaxed) |
| 1326 |
} |
| 1327 |
|
| 1328 |
/// Returns `true` if senders belong to the same channel. |
| 1329 |
/// |
| 1330 |
/// # Examples |
| 1331 |
/// |
| 1332 |
/// ``` |
| 1333 |
/// let (tx, rx) = tokio::sync::watch::channel(true); |
| 1334 |
/// let tx2 = tx.clone(); |
| 1335 |
/// assert!(tx.same_channel(&tx2)); |
| 1336 |
/// |
| 1337 |
/// let (tx3, rx3) = tokio::sync::watch::channel(true); |
| 1338 |
/// assert!(!tx3.same_channel(&tx2)); |
| 1339 |
/// ``` |
| 1340 |
pub fn same_channel(&self, other: &Self) -> bool { |
| 1341 |
Arc::ptr_eq(&self.shared, &other.shared) |
| 1342 |
} |
| 1343 |
} |
| 1344 |
|
| 1345 |
impl<T> Drop for Sender<T> { |
| 1346 |
fn drop(&mut self) { |
| 1347 |
if self.shared.ref_count_tx.fetch_sub(1, AcqRel) == 1 { |
| 1348 |
self.shared.state.set_closed(); |
| 1349 |
self.shared.notify_rx.notify_waiters(); |
| 1350 |
} |
| 1351 |
} |
| 1352 |
} |
| 1353 |
|
| 1354 |
// ===== impl Ref ===== |
| 1355 |
|
| 1356 |
impl<T> ops::Deref for Ref<'_, T> { |
| 1357 |
type Target = T; |
| 1358 |
|
| 1359 |
fn deref(&self) -> &T { |
| 1360 |
self.inner.deref() |
| 1361 |
} |
| 1362 |
} |
| 1363 |
|
| 1364 |
#[cfg(all(test, loom))] |
| 1365 |
mod tests { |
| 1366 |
use futures::future::FutureExt; |
| 1367 |
use loom::thread; |
| 1368 |
|
| 1369 |
// test for https://github.com/tokio-rs/tokio/issues/3168 |
| 1370 |
#[test] |
| 1371 |
fn watch_spurious_wakeup() { |
| 1372 |
loom::model(|| { |
| 1373 |
let (send, mut recv) = crate::sync::watch::channel(0i32); |
| 1374 |
|
| 1375 |
send.send(1).unwrap(); |
| 1376 |
|
| 1377 |
let send_thread = thread::spawn(move || { |
| 1378 |
send.send(2).unwrap(); |
| 1379 |
send |
| 1380 |
}); |
| 1381 |
|
| 1382 |
recv.changed().now_or_never(); |
| 1383 |
|
| 1384 |
let send = send_thread.join().unwrap(); |
| 1385 |
let recv_thread = thread::spawn(move || { |
| 1386 |
recv.changed().now_or_never(); |
| 1387 |
recv.changed().now_or_never(); |
| 1388 |
recv |
| 1389 |
}); |
| 1390 |
|
| 1391 |
send.send(3).unwrap(); |
| 1392 |
|
| 1393 |
let mut recv = recv_thread.join().unwrap(); |
| 1394 |
let send_thread = thread::spawn(move || { |
| 1395 |
send.send(2).unwrap(); |
| 1396 |
}); |
| 1397 |
|
| 1398 |
recv.changed().now_or_never(); |
| 1399 |
|
| 1400 |
send_thread.join().unwrap(); |
| 1401 |
}); |
| 1402 |
} |
| 1403 |
|
| 1404 |
#[test] |
| 1405 |
fn watch_borrow() { |
| 1406 |
loom::model(|| { |
| 1407 |
let (send, mut recv) = crate::sync::watch::channel(0i32); |
| 1408 |
|
| 1409 |
assert!(send.borrow().eq(&0)); |
| 1410 |
assert!(recv.borrow().eq(&0)); |
| 1411 |
|
| 1412 |
send.send(1).unwrap(); |
| 1413 |
assert!(send.borrow().eq(&1)); |
| 1414 |
|
| 1415 |
let send_thread = thread::spawn(move || { |
| 1416 |
send.send(2).unwrap(); |
| 1417 |
send |
| 1418 |
}); |
| 1419 |
|
| 1420 |
recv.changed().now_or_never(); |
| 1421 |
|
| 1422 |
let send = send_thread.join().unwrap(); |
| 1423 |
let recv_thread = thread::spawn(move || { |
| 1424 |
recv.changed().now_or_never(); |
| 1425 |
recv.changed().now_or_never(); |
| 1426 |
recv |
| 1427 |
}); |
| 1428 |
|
| 1429 |
send.send(3).unwrap(); |
| 1430 |
|
| 1431 |
let recv = recv_thread.join().unwrap(); |
| 1432 |
assert!(recv.borrow().eq(&3)); |
| 1433 |
assert!(send.borrow().eq(&3)); |
| 1434 |
|
| 1435 |
send.send(2).unwrap(); |
| 1436 |
|
| 1437 |
thread::spawn(move || { |
| 1438 |
assert!(recv.borrow().eq(&2)); |
| 1439 |
}); |
| 1440 |
assert!(send.borrow().eq(&2)); |
| 1441 |
}); |
| 1442 |
} |
| 1443 |
} |