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