| 1 |
use crate::loom::sync::Arc; |
| 2 |
use crate::sync::batch_semaphore::{self as semaphore, TryAcquireError}; |
| 3 |
use crate::sync::mpsc::chan; |
| 4 |
use crate::sync::mpsc::error::{SendError, TryRecvError, TrySendError}; |
| 5 |
|
| 6 |
cfg_time! { |
| 7 |
use crate::sync::mpsc::error::SendTimeoutError; |
| 8 |
use crate::time::Duration; |
| 9 |
} |
| 10 |
|
| 11 |
use std::fmt; |
| 12 |
use std::task::{Context, Poll}; |
| 13 |
|
| 14 |
/// Sends values to the associated `Receiver`. |
| 15 |
/// |
| 16 |
/// Instances are created by the [`channel`] function. |
| 17 |
/// |
| 18 |
/// To convert the `Sender` into a `Sink` or use it in a poll function, you can |
| 19 |
/// use the [`PollSender`] utility. |
| 20 |
/// |
| 21 |
/// [`PollSender`]: https://docs.rs/tokio-util/latest/tokio_util/sync/struct.PollSender.html |
| 22 |
pub struct Sender<T> { |
| 23 |
chan: chan::Tx<T, Semaphore>, |
| 24 |
} |
| 25 |
|
| 26 |
/// A sender that does not prevent the channel from being closed. |
| 27 |
/// |
| 28 |
/// If all [`Sender`] instances of a channel were dropped and only `WeakSender` |
| 29 |
/// instances remain, the channel is closed. |
| 30 |
/// |
| 31 |
/// In order to send messages, the `WeakSender` needs to be upgraded using |
| 32 |
/// [`WeakSender::upgrade`], which returns `Option<Sender>`. It returns `None` |
| 33 |
/// if all `Sender`s have been dropped, and otherwise it returns a `Sender`. |
| 34 |
/// |
| 35 |
/// [`Sender`]: Sender |
| 36 |
/// [`WeakSender::upgrade`]: WeakSender::upgrade |
| 37 |
/// |
| 38 |
/// # Examples |
| 39 |
/// |
| 40 |
/// ``` |
| 41 |
/// use tokio::sync::mpsc::channel; |
| 42 |
/// |
| 43 |
/// #[tokio::main] |
| 44 |
/// async fn main() { |
| 45 |
/// let (tx, _rx) = channel::<i32>(15); |
| 46 |
/// let tx_weak = tx.downgrade(); |
| 47 |
/// |
| 48 |
/// // Upgrading will succeed because `tx` still exists. |
| 49 |
/// assert!(tx_weak.upgrade().is_some()); |
| 50 |
/// |
| 51 |
/// // If we drop `tx`, then it will fail. |
| 52 |
/// drop(tx); |
| 53 |
/// assert!(tx_weak.clone().upgrade().is_none()); |
| 54 |
/// } |
| 55 |
/// ``` |
| 56 |
pub struct WeakSender<T> { |
| 57 |
chan: Arc<chan::Chan<T, Semaphore>>, |
| 58 |
} |
| 59 |
|
| 60 |
/// Permits to send one value into the channel. |
| 61 |
/// |
| 62 |
/// `Permit` values are returned by [`Sender::reserve()`] and [`Sender::try_reserve()`] |
| 63 |
/// and are used to guarantee channel capacity before generating a message to send. |
| 64 |
/// |
| 65 |
/// [`Sender::reserve()`]: Sender::reserve |
| 66 |
/// [`Sender::try_reserve()`]: Sender::try_reserve |
| 67 |
pub struct Permit<'a, T> { |
| 68 |
chan: &'a chan::Tx<T, Semaphore>, |
| 69 |
} |
| 70 |
|
| 71 |
/// An [`Iterator`] of [`Permit`] that can be used to hold `n` slots in the channel. |
| 72 |
/// |
| 73 |
/// `PermitIterator` values are returned by [`Sender::reserve_many()`] and [`Sender::try_reserve_many()`] |
| 74 |
/// and are used to guarantee channel capacity before generating `n` messages to send. |
| 75 |
/// |
| 76 |
/// [`Sender::reserve_many()`]: Sender::reserve_many |
| 77 |
/// [`Sender::try_reserve_many()`]: Sender::try_reserve_many |
| 78 |
pub struct PermitIterator<'a, T> { |
| 79 |
chan: &'a chan::Tx<T, Semaphore>, |
| 80 |
n: usize, |
| 81 |
} |
| 82 |
|
| 83 |
/// Owned permit to send one value into the channel. |
| 84 |
/// |
| 85 |
/// This is identical to the [`Permit`] type, except that it moves the sender |
| 86 |
/// rather than borrowing it. |
| 87 |
/// |
| 88 |
/// `OwnedPermit` values are returned by [`Sender::reserve_owned()`] and |
| 89 |
/// [`Sender::try_reserve_owned()`] and are used to guarantee channel capacity |
| 90 |
/// before generating a message to send. |
| 91 |
/// |
| 92 |
/// [`Permit`]: Permit |
| 93 |
/// [`Sender::reserve_owned()`]: Sender::reserve_owned |
| 94 |
/// [`Sender::try_reserve_owned()`]: Sender::try_reserve_owned |
| 95 |
pub struct OwnedPermit<T> { |
| 96 |
chan: Option<chan::Tx<T, Semaphore>>, |
| 97 |
} |
| 98 |
|
| 99 |
/// Receives values from the associated `Sender`. |
| 100 |
/// |
| 101 |
/// Instances are created by the [`channel`] function. |
| 102 |
/// |
| 103 |
/// This receiver can be turned into a `Stream` using [`ReceiverStream`]. |
| 104 |
/// |
| 105 |
/// [`ReceiverStream`]: https://docs.rs/tokio-stream/0.1/tokio_stream/wrappers/struct.ReceiverStream.html |
| 106 |
pub struct Receiver<T> { |
| 107 |
/// The channel receiver. |
| 108 |
chan: chan::Rx<T, Semaphore>, |
| 109 |
} |
| 110 |
|
| 111 |
/// Creates a bounded mpsc channel for communicating between asynchronous tasks |
| 112 |
/// with backpressure. |
| 113 |
/// |
| 114 |
/// The channel will buffer up to the provided number of messages. Once the |
| 115 |
/// buffer is full, attempts to send new messages will wait until a message is |
| 116 |
/// received from the channel. The provided buffer capacity must be at least 1. |
| 117 |
/// |
| 118 |
/// All data sent on `Sender` will become available on `Receiver` in the same |
| 119 |
/// order as it was sent. |
| 120 |
/// |
| 121 |
/// The `Sender` can be cloned to `send` to the same channel from multiple code |
| 122 |
/// locations. Only one `Receiver` is supported. |
| 123 |
/// |
| 124 |
/// If the `Receiver` is disconnected while trying to `send`, the `send` method |
| 125 |
/// will return a `SendError`. Similarly, if `Sender` is disconnected while |
| 126 |
/// trying to `recv`, the `recv` method will return `None`. |
| 127 |
/// |
| 128 |
/// # Panics |
| 129 |
/// |
| 130 |
/// Panics if the buffer capacity is 0. |
| 131 |
/// |
| 132 |
/// # Examples |
| 133 |
/// |
| 134 |
/// ```rust |
| 135 |
/// use tokio::sync::mpsc; |
| 136 |
/// |
| 137 |
/// #[tokio::main] |
| 138 |
/// async fn main() { |
| 139 |
/// let (tx, mut rx) = mpsc::channel(100); |
| 140 |
/// |
| 141 |
/// tokio::spawn(async move { |
| 142 |
/// for i in 0..10 { |
| 143 |
/// if let Err(_) = tx.send(i).await { |
| 144 |
/// println!("receiver dropped"); |
| 145 |
/// return; |
| 146 |
/// } |
| 147 |
/// } |
| 148 |
/// }); |
| 149 |
/// |
| 150 |
/// while let Some(i) = rx.recv().await { |
| 151 |
/// println!("got = {}", i); |
| 152 |
/// } |
| 153 |
/// } |
| 154 |
/// ``` |
| 155 |
#[track_caller] |
| 156 |
pub fn channel<T>(buffer: usize) -> (Sender<T>, Receiver<T>) { |
| 157 |
assert!(buffer > 0, "mpsc bounded channel requires buffer > 0"); |
| 158 |
let semaphore = Semaphore { |
| 159 |
semaphore: semaphore::Semaphore::new(buffer), |
| 160 |
bound: buffer, |
| 161 |
}; |
| 162 |
let (tx, rx) = chan::channel(semaphore); |
| 163 |
|
| 164 |
let tx = Sender::new(tx); |
| 165 |
let rx = Receiver::new(rx); |
| 166 |
|
| 167 |
(tx, rx) |
| 168 |
} |
| 169 |
|
| 170 |
/// Channel semaphore is a tuple of the semaphore implementation and a `usize` |
| 171 |
/// representing the channel bound. |
| 172 |
#[derive(Debug)] |
| 173 |
pub(crate) struct Semaphore { |
| 174 |
pub(crate) semaphore: semaphore::Semaphore, |
| 175 |
pub(crate) bound: usize, |
| 176 |
} |
| 177 |
|
| 178 |
impl<T> Receiver<T> { |
| 179 |
pub(crate) fn new(chan: chan::Rx<T, Semaphore>) -> Receiver<T> { |
| 180 |
Receiver { chan } |
| 181 |
} |
| 182 |
|
| 183 |
/// Receives the next value for this receiver. |
| 184 |
/// |
| 185 |
/// This method returns `None` if the channel has been closed and there are |
| 186 |
/// no remaining messages in the channel's buffer. This indicates that no |
| 187 |
/// further values can ever be received from this `Receiver`. The channel is |
| 188 |
/// closed when all senders have been dropped, or when [`close`] is called. |
| 189 |
/// |
| 190 |
/// If there are no messages in the channel's buffer, but the channel has |
| 191 |
/// not yet been closed, this method will sleep until a message is sent or |
| 192 |
/// the channel is closed. Note that if [`close`] is called, but there are |
| 193 |
/// still outstanding [`Permits`] from before it was closed, the channel is |
| 194 |
/// not considered closed by `recv` until the permits are released. |
| 195 |
/// |
| 196 |
/// # Cancel safety |
| 197 |
/// |
| 198 |
/// This method is cancel safe. If `recv` is used as the event in a |
| 199 |
/// [`tokio::select!`](crate::select) statement and some other branch |
| 200 |
/// completes first, it is guaranteed that no messages were received on this |
| 201 |
/// channel. |
| 202 |
/// |
| 203 |
/// [`close`]: Self::close |
| 204 |
/// [`Permits`]: struct@crate::sync::mpsc::Permit |
| 205 |
/// |
| 206 |
/// # Examples |
| 207 |
/// |
| 208 |
/// ``` |
| 209 |
/// use tokio::sync::mpsc; |
| 210 |
/// |
| 211 |
/// #[tokio::main] |
| 212 |
/// async fn main() { |
| 213 |
/// let (tx, mut rx) = mpsc::channel(100); |
| 214 |
/// |
| 215 |
/// tokio::spawn(async move { |
| 216 |
/// tx.send("hello").await.unwrap(); |
| 217 |
/// }); |
| 218 |
/// |
| 219 |
/// assert_eq!(Some("hello"), rx.recv().await); |
| 220 |
/// assert_eq!(None, rx.recv().await); |
| 221 |
/// } |
| 222 |
/// ``` |
| 223 |
/// |
| 224 |
/// Values are buffered: |
| 225 |
/// |
| 226 |
/// ``` |
| 227 |
/// use tokio::sync::mpsc; |
| 228 |
/// |
| 229 |
/// #[tokio::main] |
| 230 |
/// async fn main() { |
| 231 |
/// let (tx, mut rx) = mpsc::channel(100); |
| 232 |
/// |
| 233 |
/// tx.send("hello").await.unwrap(); |
| 234 |
/// tx.send("world").await.unwrap(); |
| 235 |
/// |
| 236 |
/// assert_eq!(Some("hello"), rx.recv().await); |
| 237 |
/// assert_eq!(Some("world"), rx.recv().await); |
| 238 |
/// } |
| 239 |
/// ``` |
| 240 |
pub async fn recv(&mut self) -> Option<T> { |
| 241 |
use crate::future::poll_fn; |
| 242 |
poll_fn(|cx| self.chan.recv(cx)).await |
| 243 |
} |
| 244 |
|
| 245 |
/// Receives the next values for this receiver and extends `buffer`. |
| 246 |
/// |
| 247 |
/// This method extends `buffer` by no more than a fixed number of values |
| 248 |
/// as specified by `limit`. If `limit` is zero, the function immediately |
| 249 |
/// returns `0`. The return value is the number of values added to `buffer`. |
| 250 |
/// |
| 251 |
/// For `limit > 0`, if there are no messages in the channel's queue, but |
| 252 |
/// the channel has not yet been closed, this method will sleep until a |
| 253 |
/// message is sent or the channel is closed. Note that if [`close`] is |
| 254 |
/// called, but there are still outstanding [`Permits`] from before it was |
| 255 |
/// closed, the channel is not considered closed by `recv_many` until the |
| 256 |
/// permits are released. |
| 257 |
/// |
| 258 |
/// For non-zero values of `limit`, this method will never return `0` unless |
| 259 |
/// the channel has been closed and there are no remaining messages in the |
| 260 |
/// channel's queue. This indicates that no further values can ever be |
| 261 |
/// received from this `Receiver`. The channel is closed when all senders |
| 262 |
/// have been dropped, or when [`close`] is called. |
| 263 |
/// |
| 264 |
/// The capacity of `buffer` is increased as needed. |
| 265 |
/// |
| 266 |
/// # Cancel safety |
| 267 |
/// |
| 268 |
/// This method is cancel safe. If `recv_many` is used as the event in a |
| 269 |
/// [`tokio::select!`](crate::select) statement and some other branch |
| 270 |
/// completes first, it is guaranteed that no messages were received on this |
| 271 |
/// channel. |
| 272 |
/// |
| 273 |
/// [`close`]: Self::close |
| 274 |
/// [`Permits`]: struct@crate::sync::mpsc::Permit |
| 275 |
/// |
| 276 |
/// # Examples |
| 277 |
/// |
| 278 |
/// ``` |
| 279 |
/// use tokio::sync::mpsc; |
| 280 |
/// |
| 281 |
/// #[tokio::main] |
| 282 |
/// async fn main() { |
| 283 |
/// let mut buffer: Vec<&str> = Vec::with_capacity(2); |
| 284 |
/// let limit = 2; |
| 285 |
/// let (tx, mut rx) = mpsc::channel(100); |
| 286 |
/// let tx2 = tx.clone(); |
| 287 |
/// tx2.send("first").await.unwrap(); |
| 288 |
/// tx2.send("second").await.unwrap(); |
| 289 |
/// tx2.send("third").await.unwrap(); |
| 290 |
/// |
| 291 |
/// // Call `recv_many` to receive up to `limit` (2) values. |
| 292 |
/// assert_eq!(2, rx.recv_many(&mut buffer, limit).await); |
| 293 |
/// assert_eq!(vec!["first", "second"], buffer); |
| 294 |
/// |
| 295 |
/// // If the buffer is full, the next call to `recv_many` |
| 296 |
/// // reserves additional capacity. |
| 297 |
/// assert_eq!(1, rx.recv_many(&mut buffer, 1).await); |
| 298 |
/// |
| 299 |
/// tokio::spawn(async move { |
| 300 |
/// tx.send("fourth").await.unwrap(); |
| 301 |
/// }); |
| 302 |
/// |
| 303 |
/// // 'tx' is dropped, but `recv_many` |
| 304 |
/// // is guaranteed not to return 0 as the channel |
| 305 |
/// // is not yet closed. |
| 306 |
/// assert_eq!(1, rx.recv_many(&mut buffer, 1).await); |
| 307 |
/// assert_eq!(vec!["first", "second", "third", "fourth"], buffer); |
| 308 |
/// |
| 309 |
/// // Once the last sender is dropped, the channel is |
| 310 |
/// // closed and `recv_many` returns 0, capacity unchanged. |
| 311 |
/// drop(tx2); |
| 312 |
/// assert_eq!(0, rx.recv_many(&mut buffer, limit).await); |
| 313 |
/// assert_eq!(vec!["first", "second", "third", "fourth"], buffer); |
| 314 |
/// } |
| 315 |
/// ``` |
| 316 |
pub async fn recv_many(&mut self, buffer: &mut Vec<T>, limit: usize) -> usize { |
| 317 |
use crate::future::poll_fn; |
| 318 |
poll_fn(|cx| self.chan.recv_many(cx, buffer, limit)).await |
| 319 |
} |
| 320 |
|
| 321 |
/// Tries to receive the next value for this receiver. |
| 322 |
/// |
| 323 |
/// This method returns the [`Empty`] error if the channel is currently |
| 324 |
/// empty, but there are still outstanding [senders] or [permits]. |
| 325 |
/// |
| 326 |
/// This method returns the [`Disconnected`] error if the channel is |
| 327 |
/// currently empty, and there are no outstanding [senders] or [permits]. |
| 328 |
/// |
| 329 |
/// Unlike the [`poll_recv`] method, this method will never return an |
| 330 |
/// [`Empty`] error spuriously. |
| 331 |
/// |
| 332 |
/// [`Empty`]: crate::sync::mpsc::error::TryRecvError::Empty |
| 333 |
/// [`Disconnected`]: crate::sync::mpsc::error::TryRecvError::Disconnected |
| 334 |
/// [`poll_recv`]: Self::poll_recv |
| 335 |
/// [senders]: crate::sync::mpsc::Sender |
| 336 |
/// [permits]: crate::sync::mpsc::Permit |
| 337 |
/// |
| 338 |
/// # Examples |
| 339 |
/// |
| 340 |
/// ``` |
| 341 |
/// use tokio::sync::mpsc; |
| 342 |
/// use tokio::sync::mpsc::error::TryRecvError; |
| 343 |
/// |
| 344 |
/// #[tokio::main] |
| 345 |
/// async fn main() { |
| 346 |
/// let (tx, mut rx) = mpsc::channel(100); |
| 347 |
/// |
| 348 |
/// tx.send("hello").await.unwrap(); |
| 349 |
/// |
| 350 |
/// assert_eq!(Ok("hello"), rx.try_recv()); |
| 351 |
/// assert_eq!(Err(TryRecvError::Empty), rx.try_recv()); |
| 352 |
/// |
| 353 |
/// tx.send("hello").await.unwrap(); |
| 354 |
/// // Drop the last sender, closing the channel. |
| 355 |
/// drop(tx); |
| 356 |
/// |
| 357 |
/// assert_eq!(Ok("hello"), rx.try_recv()); |
| 358 |
/// assert_eq!(Err(TryRecvError::Disconnected), rx.try_recv()); |
| 359 |
/// } |
| 360 |
/// ``` |
| 361 |
pub fn try_recv(&mut self) -> Result<T, TryRecvError> { |
| 362 |
self.chan.try_recv() |
| 363 |
} |
| 364 |
|
| 365 |
/// Blocking receive to call outside of asynchronous contexts. |
| 366 |
/// |
| 367 |
/// This method returns `None` if the channel has been closed and there are |
| 368 |
/// no remaining messages in the channel's buffer. This indicates that no |
| 369 |
/// further values can ever be received from this `Receiver`. The channel is |
| 370 |
/// closed when all senders have been dropped, or when [`close`] is called. |
| 371 |
/// |
| 372 |
/// If there are no messages in the channel's buffer, but the channel has |
| 373 |
/// not yet been closed, this method will block until a message is sent or |
| 374 |
/// the channel is closed. |
| 375 |
/// |
| 376 |
/// This method is intended for use cases where you are sending from |
| 377 |
/// asynchronous code to synchronous code, and will work even if the sender |
| 378 |
/// is not using [`blocking_send`] to send the message. |
| 379 |
/// |
| 380 |
/// Note that if [`close`] is called, but there are still outstanding |
| 381 |
/// [`Permits`] from before it was closed, the channel is not considered |
| 382 |
/// closed by `blocking_recv` until the permits are released. |
| 383 |
/// |
| 384 |
/// [`close`]: Self::close |
| 385 |
/// [`Permits`]: struct@crate::sync::mpsc::Permit |
| 386 |
/// [`blocking_send`]: fn@crate::sync::mpsc::Sender::blocking_send |
| 387 |
/// |
| 388 |
/// # Panics |
| 389 |
/// |
| 390 |
/// This function panics if called within an asynchronous execution |
| 391 |
/// context. |
| 392 |
/// |
| 393 |
/// # Examples |
| 394 |
/// |
| 395 |
/// ``` |
| 396 |
/// use std::thread; |
| 397 |
/// use tokio::runtime::Runtime; |
| 398 |
/// use tokio::sync::mpsc; |
| 399 |
/// |
| 400 |
/// fn main() { |
| 401 |
/// let (tx, mut rx) = mpsc::channel::<u8>(10); |
| 402 |
/// |
| 403 |
/// let sync_code = thread::spawn(move || { |
| 404 |
/// assert_eq!(Some(10), rx.blocking_recv()); |
| 405 |
/// }); |
| 406 |
/// |
| 407 |
/// Runtime::new() |
| 408 |
/// .unwrap() |
| 409 |
/// .block_on(async move { |
| 410 |
/// let _ = tx.send(10).await; |
| 411 |
/// }); |
| 412 |
/// sync_code.join().unwrap() |
| 413 |
/// } |
| 414 |
/// ``` |
| 415 |
#[track_caller] |
| 416 |
#[cfg(feature = "sync")] |
| 417 |
#[cfg_attr(docsrs, doc(alias = "recv_blocking"))] |
| 418 |
pub fn blocking_recv(&mut self) -> Option<T> { |
| 419 |
crate::future::block_on(self.recv()) |
| 420 |
} |
| 421 |
|
| 422 |
/// Closes the receiving half of a channel without dropping it. |
| 423 |
/// |
| 424 |
/// This prevents any further messages from being sent on the channel while |
| 425 |
/// still enabling the receiver to drain messages that are buffered. Any |
| 426 |
/// outstanding [`Permit`] values will still be able to send messages. |
| 427 |
/// |
| 428 |
/// To guarantee that no messages are dropped, after calling `close()`, |
| 429 |
/// `recv()` must be called until `None` is returned. If there are |
| 430 |
/// outstanding [`Permit`] or [`OwnedPermit`] values, the `recv` method will |
| 431 |
/// not return `None` until those are released. |
| 432 |
/// |
| 433 |
/// [`Permit`]: Permit |
| 434 |
/// [`OwnedPermit`]: OwnedPermit |
| 435 |
/// |
| 436 |
/// # Examples |
| 437 |
/// |
| 438 |
/// ``` |
| 439 |
/// use tokio::sync::mpsc; |
| 440 |
/// |
| 441 |
/// #[tokio::main] |
| 442 |
/// async fn main() { |
| 443 |
/// let (tx, mut rx) = mpsc::channel(20); |
| 444 |
/// |
| 445 |
/// tokio::spawn(async move { |
| 446 |
/// let mut i = 0; |
| 447 |
/// while let Ok(permit) = tx.reserve().await { |
| 448 |
/// permit.send(i); |
| 449 |
/// i += 1; |
| 450 |
/// } |
| 451 |
/// }); |
| 452 |
/// |
| 453 |
/// rx.close(); |
| 454 |
/// |
| 455 |
/// while let Some(msg) = rx.recv().await { |
| 456 |
/// println!("got {}", msg); |
| 457 |
/// } |
| 458 |
/// |
| 459 |
/// // Channel closed and no messages are lost. |
| 460 |
/// } |
| 461 |
/// ``` |
| 462 |
pub fn close(&mut self) { |
| 463 |
self.chan.close(); |
| 464 |
} |
| 465 |
|
| 466 |
/// Checks if a channel is closed. |
| 467 |
/// |
| 468 |
/// This method returns `true` if the channel has been closed. The channel is closed |
| 469 |
/// when all [`Sender`] have been dropped, or when [`Receiver::close`] is called. |
| 470 |
/// |
| 471 |
/// [`Sender`]: crate::sync::mpsc::Sender |
| 472 |
/// [`Receiver::close`]: crate::sync::mpsc::Receiver::close |
| 473 |
/// |
| 474 |
/// # Examples |
| 475 |
/// ``` |
| 476 |
/// use tokio::sync::mpsc; |
| 477 |
/// |
| 478 |
/// #[tokio::main] |
| 479 |
/// async fn main() { |
| 480 |
/// let (_tx, mut rx) = mpsc::channel::<()>(10); |
| 481 |
/// assert!(!rx.is_closed()); |
| 482 |
/// |
| 483 |
/// rx.close(); |
| 484 |
/// |
| 485 |
/// assert!(rx.is_closed()); |
| 486 |
/// } |
| 487 |
/// ``` |
| 488 |
pub fn is_closed(&self) -> bool { |
| 489 |
self.chan.is_closed() |
| 490 |
} |
| 491 |
|
| 492 |
/// Checks if a channel is empty. |
| 493 |
/// |
| 494 |
/// This method returns `true` if the channel has no messages. |
| 495 |
/// |
| 496 |
/// # Examples |
| 497 |
/// ``` |
| 498 |
/// use tokio::sync::mpsc; |
| 499 |
/// |
| 500 |
/// #[tokio::main] |
| 501 |
/// async fn main() { |
| 502 |
/// let (tx, rx) = mpsc::channel(10); |
| 503 |
/// assert!(rx.is_empty()); |
| 504 |
/// |
| 505 |
/// tx.send(0).await.unwrap(); |
| 506 |
/// assert!(!rx.is_empty()); |
| 507 |
/// } |
| 508 |
/// |
| 509 |
/// ``` |
| 510 |
pub fn is_empty(&self) -> bool { |
| 511 |
self.chan.is_empty() |
| 512 |
} |
| 513 |
|
| 514 |
/// Returns the number of messages in the channel. |
| 515 |
/// |
| 516 |
/// # Examples |
| 517 |
/// ``` |
| 518 |
/// use tokio::sync::mpsc; |
| 519 |
/// |
| 520 |
/// #[tokio::main] |
| 521 |
/// async fn main() { |
| 522 |
/// let (tx, rx) = mpsc::channel(10); |
| 523 |
/// assert_eq!(0, rx.len()); |
| 524 |
/// |
| 525 |
/// tx.send(0).await.unwrap(); |
| 526 |
/// assert_eq!(1, rx.len()); |
| 527 |
/// } |
| 528 |
/// ``` |
| 529 |
pub fn len(&self) -> usize { |
| 530 |
self.chan.len() |
| 531 |
} |
| 532 |
|
| 533 |
/// Returns the current capacity of the channel. |
| 534 |
/// |
| 535 |
/// The capacity goes down when the sender sends a value by calling [`Sender::send`] or by reserving |
| 536 |
/// capacity with [`Sender::reserve`]. The capacity goes up when values are received. |
| 537 |
/// This is distinct from [`max_capacity`], which always returns buffer capacity initially |
| 538 |
/// specified when calling [`channel`]. |
| 539 |
/// |
| 540 |
/// # Examples |
| 541 |
/// |
| 542 |
/// ``` |
| 543 |
/// use tokio::sync::mpsc; |
| 544 |
/// |
| 545 |
/// #[tokio::main] |
| 546 |
/// async fn main() { |
| 547 |
/// let (tx, mut rx) = mpsc::channel::<()>(5); |
| 548 |
/// |
| 549 |
/// assert_eq!(rx.capacity(), 5); |
| 550 |
/// |
| 551 |
/// // Making a reservation drops the capacity by one. |
| 552 |
/// let permit = tx.reserve().await.unwrap(); |
| 553 |
/// assert_eq!(rx.capacity(), 4); |
| 554 |
/// assert_eq!(rx.len(), 0); |
| 555 |
/// |
| 556 |
/// // Sending and receiving a value increases the capacity by one. |
| 557 |
/// permit.send(()); |
| 558 |
/// assert_eq!(rx.len(), 1); |
| 559 |
/// rx.recv().await.unwrap(); |
| 560 |
/// assert_eq!(rx.capacity(), 5); |
| 561 |
/// |
| 562 |
/// // Directly sending a message drops the capacity by one. |
| 563 |
/// tx.send(()).await.unwrap(); |
| 564 |
/// assert_eq!(rx.capacity(), 4); |
| 565 |
/// assert_eq!(rx.len(), 1); |
| 566 |
/// |
| 567 |
/// // Receiving the message increases the capacity by one. |
| 568 |
/// rx.recv().await.unwrap(); |
| 569 |
/// assert_eq!(rx.capacity(), 5); |
| 570 |
/// assert_eq!(rx.len(), 0); |
| 571 |
/// } |
| 572 |
/// ``` |
| 573 |
/// [`capacity`]: Receiver::capacity |
| 574 |
/// [`max_capacity`]: Receiver::max_capacity |
| 575 |
pub fn capacity(&self) -> usize { |
| 576 |
self.chan.semaphore().semaphore.available_permits() |
| 577 |
} |
| 578 |
|
| 579 |
/// Returns the maximum buffer capacity of the channel. |
| 580 |
/// |
| 581 |
/// The maximum capacity is the buffer capacity initially specified when calling |
| 582 |
/// [`channel`]. This is distinct from [`capacity`], which returns the *current* |
| 583 |
/// available buffer capacity: as messages are sent and received, the value |
| 584 |
/// returned by [`capacity`] will go up or down, whereas the value |
| 585 |
/// returned by [`max_capacity`] will remain constant. |
| 586 |
/// |
| 587 |
/// # Examples |
| 588 |
/// |
| 589 |
/// ``` |
| 590 |
/// use tokio::sync::mpsc; |
| 591 |
/// |
| 592 |
/// #[tokio::main] |
| 593 |
/// async fn main() { |
| 594 |
/// let (tx, rx) = mpsc::channel::<()>(5); |
| 595 |
/// |
| 596 |
/// // both max capacity and capacity are the same at first |
| 597 |
/// assert_eq!(rx.max_capacity(), 5); |
| 598 |
/// assert_eq!(rx.capacity(), 5); |
| 599 |
/// |
| 600 |
/// // Making a reservation doesn't change the max capacity. |
| 601 |
/// let permit = tx.reserve().await.unwrap(); |
| 602 |
/// assert_eq!(rx.max_capacity(), 5); |
| 603 |
/// // but drops the capacity by one |
| 604 |
/// assert_eq!(rx.capacity(), 4); |
| 605 |
/// } |
| 606 |
/// ``` |
| 607 |
/// [`capacity`]: Receiver::capacity |
| 608 |
/// [`max_capacity`]: Receiver::max_capacity |
| 609 |
pub fn max_capacity(&self) -> usize { |
| 610 |
self.chan.semaphore().bound |
| 611 |
} |
| 612 |
|
| 613 |
/// Polls to receive the next message on this channel. |
| 614 |
/// |
| 615 |
/// This method returns: |
| 616 |
/// |
| 617 |
/// * `Poll::Pending` if no messages are available but the channel is not |
| 618 |
/// closed, or if a spurious failure happens. |
| 619 |
/// * `Poll::Ready(Some(message))` if a message is available. |
| 620 |
/// * `Poll::Ready(None)` if the channel has been closed and all messages |
| 621 |
/// sent before it was closed have been received. |
| 622 |
/// |
| 623 |
/// When the method returns `Poll::Pending`, the `Waker` in the provided |
| 624 |
/// `Context` is scheduled to receive a wakeup when a message is sent on any |
| 625 |
/// receiver, or when the channel is closed. Note that on multiple calls to |
| 626 |
/// `poll_recv` or `poll_recv_many`, only the `Waker` from the `Context` |
| 627 |
/// passed to the most recent call is scheduled to receive a wakeup. |
| 628 |
/// |
| 629 |
/// If this method returns `Poll::Pending` due to a spurious failure, then |
| 630 |
/// the `Waker` will be notified when the situation causing the spurious |
| 631 |
/// failure has been resolved. Note that receiving such a wakeup does not |
| 632 |
/// guarantee that the next call will succeed — it could fail with another |
| 633 |
/// spurious failure. |
| 634 |
pub fn poll_recv(&mut self, cx: &mut Context<'_>) -> Poll<Option<T>> { |
| 635 |
self.chan.recv(cx) |
| 636 |
} |
| 637 |
|
| 638 |
/// Polls to receive multiple messages on this channel, extending the provided buffer. |
| 639 |
/// |
| 640 |
/// This method returns: |
| 641 |
/// * `Poll::Pending` if no messages are available but the channel is not closed, or if a |
| 642 |
/// spurious failure happens. |
| 643 |
/// * `Poll::Ready(count)` where `count` is the number of messages successfully received and |
| 644 |
/// stored in `buffer`. This can be less than, or equal to, `limit`. |
| 645 |
/// * `Poll::Ready(0)` if `limit` is set to zero or when the channel is closed. |
| 646 |
/// |
| 647 |
/// When the method returns `Poll::Pending`, the `Waker` in the provided |
| 648 |
/// `Context` is scheduled to receive a wakeup when a message is sent on any |
| 649 |
/// receiver, or when the channel is closed. Note that on multiple calls to |
| 650 |
/// `poll_recv` or `poll_recv_many`, only the `Waker` from the `Context` |
| 651 |
/// passed to the most recent call is scheduled to receive a wakeup. |
| 652 |
/// |
| 653 |
/// Note that this method does not guarantee that exactly `limit` messages |
| 654 |
/// are received. Rather, if at least one message is available, it returns |
| 655 |
/// as many messages as it can up to the given limit. This method returns |
| 656 |
/// zero only if the channel is closed (or if `limit` is zero). |
| 657 |
/// |
| 658 |
/// # Examples |
| 659 |
/// |
| 660 |
/// ``` |
| 661 |
/// use std::task::{Context, Poll}; |
| 662 |
/// use std::pin::Pin; |
| 663 |
/// use tokio::sync::mpsc; |
| 664 |
/// use futures::Future; |
| 665 |
/// |
| 666 |
/// struct MyReceiverFuture<'a> { |
| 667 |
/// receiver: mpsc::Receiver<i32>, |
| 668 |
/// buffer: &'a mut Vec<i32>, |
| 669 |
/// limit: usize, |
| 670 |
/// } |
| 671 |
/// |
| 672 |
/// impl<'a> Future for MyReceiverFuture<'a> { |
| 673 |
/// type Output = usize; // Number of messages received |
| 674 |
/// |
| 675 |
/// fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { |
| 676 |
/// let MyReceiverFuture { receiver, buffer, limit } = &mut *self; |
| 677 |
/// |
| 678 |
/// // Now `receiver` and `buffer` are mutable references, and `limit` is copied |
| 679 |
/// match receiver.poll_recv_many(cx, *buffer, *limit) { |
| 680 |
/// Poll::Pending => Poll::Pending, |
| 681 |
/// Poll::Ready(count) => Poll::Ready(count), |
| 682 |
/// } |
| 683 |
/// } |
| 684 |
/// } |
| 685 |
/// |
| 686 |
/// #[tokio::main] |
| 687 |
/// async fn main() { |
| 688 |
/// let (tx, rx) = mpsc::channel(32); |
| 689 |
/// let mut buffer = Vec::new(); |
| 690 |
/// |
| 691 |
/// let my_receiver_future = MyReceiverFuture { |
| 692 |
/// receiver: rx, |
| 693 |
/// buffer: &mut buffer, |
| 694 |
/// limit: 3, |
| 695 |
/// }; |
| 696 |
/// |
| 697 |
/// for i in 0..10 { |
| 698 |
/// tx.send(i).await.unwrap(); |
| 699 |
/// } |
| 700 |
/// |
| 701 |
/// let count = my_receiver_future.await; |
| 702 |
/// assert_eq!(count, 3); |
| 703 |
/// assert_eq!(buffer, vec![0,1,2]) |
| 704 |
/// } |
| 705 |
/// ``` |
| 706 |
pub fn poll_recv_many( |
| 707 |
&mut self, |
| 708 |
cx: &mut Context<'_>, |
| 709 |
buffer: &mut Vec<T>, |
| 710 |
limit: usize, |
| 711 |
) -> Poll<usize> { |
| 712 |
self.chan.recv_many(cx, buffer, limit) |
| 713 |
} |
| 714 |
|
| 715 |
/// Returns the number of [`Sender`] handles. |
| 716 |
pub fn sender_strong_count(&self) -> usize { |
| 717 |
self.chan.sender_strong_count() |
| 718 |
} |
| 719 |
|
| 720 |
/// Returns the number of [`WeakSender`] handles. |
| 721 |
pub fn sender_weak_count(&self) -> usize { |
| 722 |
self.chan.sender_weak_count() |
| 723 |
} |
| 724 |
} |
| 725 |
|
| 726 |
impl<T> fmt::Debug for Receiver<T> { |
| 727 |
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 728 |
fmt.debug_struct("Receiver") |
| 729 |
.field("chan", &self.chan) |
| 730 |
.finish() |
| 731 |
} |
| 732 |
} |
| 733 |
|
| 734 |
impl<T> Unpin for Receiver<T> {} |
| 735 |
|
| 736 |
impl<T> Sender<T> { |
| 737 |
pub(crate) fn new(chan: chan::Tx<T, Semaphore>) -> Sender<T> { |
| 738 |
Sender { chan } |
| 739 |
} |
| 740 |
|
| 741 |
/// Sends a value, waiting until there is capacity. |
| 742 |
/// |
| 743 |
/// A successful send occurs when it is determined that the other end of the |
| 744 |
/// channel has not hung up already. An unsuccessful send would be one where |
| 745 |
/// the corresponding receiver has already been closed. Note that a return |
| 746 |
/// value of `Err` means that the data will never be received, but a return |
| 747 |
/// value of `Ok` does not mean that the data will be received. It is |
| 748 |
/// possible for the corresponding receiver to hang up immediately after |
| 749 |
/// this function returns `Ok`. |
| 750 |
/// |
| 751 |
/// # Errors |
| 752 |
/// |
| 753 |
/// If the receive half of the channel is closed, either due to [`close`] |
| 754 |
/// being called or the [`Receiver`] handle dropping, the function returns |
| 755 |
/// an error. The error includes the value passed to `send`. |
| 756 |
/// |
| 757 |
/// [`close`]: Receiver::close |
| 758 |
/// [`Receiver`]: Receiver |
| 759 |
/// |
| 760 |
/// # Cancel safety |
| 761 |
/// |
| 762 |
/// If `send` is used as the event in a [`tokio::select!`](crate::select) |
| 763 |
/// statement and some other branch completes first, then it is guaranteed |
| 764 |
/// that the message was not sent. **However, in that case, the message |
| 765 |
/// is dropped and will be lost.** |
| 766 |
/// |
| 767 |
/// To avoid losing messages, use [`reserve`](Self::reserve) to reserve |
| 768 |
/// capacity, then use the returned [`Permit`] to send the message. |
| 769 |
/// |
| 770 |
/// This channel uses a queue to ensure that calls to `send` and `reserve` |
| 771 |
/// complete in the order they were requested. Cancelling a call to |
| 772 |
/// `send` makes you lose your place in the queue. |
| 773 |
/// |
| 774 |
/// # Examples |
| 775 |
/// |
| 776 |
/// In the following example, each call to `send` will block until the |
| 777 |
/// previously sent value was received. |
| 778 |
/// |
| 779 |
/// ```rust |
| 780 |
/// use tokio::sync::mpsc; |
| 781 |
/// |
| 782 |
/// #[tokio::main] |
| 783 |
/// async fn main() { |
| 784 |
/// let (tx, mut rx) = mpsc::channel(1); |
| 785 |
/// |
| 786 |
/// tokio::spawn(async move { |
| 787 |
/// for i in 0..10 { |
| 788 |
/// if let Err(_) = tx.send(i).await { |
| 789 |
/// println!("receiver dropped"); |
| 790 |
/// return; |
| 791 |
/// } |
| 792 |
/// } |
| 793 |
/// }); |
| 794 |
/// |
| 795 |
/// while let Some(i) = rx.recv().await { |
| 796 |
/// println!("got = {}", i); |
| 797 |
/// } |
| 798 |
/// } |
| 799 |
/// ``` |
| 800 |
pub async fn send(&self, value: T) -> Result<(), SendError<T>> { |
| 801 |
match self.reserve().await { |
| 802 |
Ok(permit) => { |
| 803 |
permit.send(value); |
| 804 |
Ok(()) |
| 805 |
} |
| 806 |
Err(_) => Err(SendError(value)), |
| 807 |
} |
| 808 |
} |
| 809 |
|
| 810 |
/// Completes when the receiver has dropped. |
| 811 |
/// |
| 812 |
/// This allows the producers to get notified when interest in the produced |
| 813 |
/// values is canceled and immediately stop doing work. |
| 814 |
/// |
| 815 |
/// # Cancel safety |
| 816 |
/// |
| 817 |
/// This method is cancel safe. Once the channel is closed, it stays closed |
| 818 |
/// forever and all future calls to `closed` will return immediately. |
| 819 |
/// |
| 820 |
/// # Examples |
| 821 |
/// |
| 822 |
/// ``` |
| 823 |
/// use tokio::sync::mpsc; |
| 824 |
/// |
| 825 |
/// #[tokio::main] |
| 826 |
/// async fn main() { |
| 827 |
/// let (tx1, rx) = mpsc::channel::<()>(1); |
| 828 |
/// let tx2 = tx1.clone(); |
| 829 |
/// let tx3 = tx1.clone(); |
| 830 |
/// let tx4 = tx1.clone(); |
| 831 |
/// let tx5 = tx1.clone(); |
| 832 |
/// tokio::spawn(async move { |
| 833 |
/// drop(rx); |
| 834 |
/// }); |
| 835 |
/// |
| 836 |
/// futures::join!( |
| 837 |
/// tx1.closed(), |
| 838 |
/// tx2.closed(), |
| 839 |
/// tx3.closed(), |
| 840 |
/// tx4.closed(), |
| 841 |
/// tx5.closed() |
| 842 |
/// ); |
| 843 |
/// println!("Receiver dropped"); |
| 844 |
/// } |
| 845 |
/// ``` |
| 846 |
pub async fn closed(&self) { |
| 847 |
self.chan.closed().await; |
| 848 |
} |
| 849 |
|
| 850 |
/// Attempts to immediately send a message on this `Sender` |
| 851 |
/// |
| 852 |
/// This method differs from [`send`] by returning immediately if the channel's |
| 853 |
/// buffer is full or no receiver is waiting to acquire some data. Compared |
| 854 |
/// with [`send`], this function has two failure cases instead of one (one for |
| 855 |
/// disconnection, one for a full buffer). |
| 856 |
/// |
| 857 |
/// # Errors |
| 858 |
/// |
| 859 |
/// If the channel capacity has been reached, i.e., the channel has `n` |
| 860 |
/// buffered values where `n` is the argument passed to [`channel`], then an |
| 861 |
/// error is returned. |
| 862 |
/// |
| 863 |
/// If the receive half of the channel is closed, either due to [`close`] |
| 864 |
/// being called or the [`Receiver`] handle dropping, the function returns |
| 865 |
/// an error. The error includes the value passed to `send`. |
| 866 |
/// |
| 867 |
/// [`send`]: Sender::send |
| 868 |
/// [`channel`]: channel |
| 869 |
/// [`close`]: Receiver::close |
| 870 |
/// |
| 871 |
/// # Examples |
| 872 |
/// |
| 873 |
/// ``` |
| 874 |
/// use tokio::sync::mpsc; |
| 875 |
/// |
| 876 |
/// #[tokio::main] |
| 877 |
/// async fn main() { |
| 878 |
/// // Create a channel with buffer size 1 |
| 879 |
/// let (tx1, mut rx) = mpsc::channel(1); |
| 880 |
/// let tx2 = tx1.clone(); |
| 881 |
/// |
| 882 |
/// tokio::spawn(async move { |
| 883 |
/// tx1.send(1).await.unwrap(); |
| 884 |
/// tx1.send(2).await.unwrap(); |
| 885 |
/// // task waits until the receiver receives a value. |
| 886 |
/// }); |
| 887 |
/// |
| 888 |
/// tokio::spawn(async move { |
| 889 |
/// // This will return an error and send |
| 890 |
/// // no message if the buffer is full |
| 891 |
/// let _ = tx2.try_send(3); |
| 892 |
/// }); |
| 893 |
/// |
| 894 |
/// let mut msg; |
| 895 |
/// msg = rx.recv().await.unwrap(); |
| 896 |
/// println!("message {} received", msg); |
| 897 |
/// |
| 898 |
/// msg = rx.recv().await.unwrap(); |
| 899 |
/// println!("message {} received", msg); |
| 900 |
/// |
| 901 |
/// // Third message may have never been sent |
| 902 |
/// match rx.recv().await { |
| 903 |
/// Some(msg) => println!("message {} received", msg), |
| 904 |
/// None => println!("the third message was never sent"), |
| 905 |
/// } |
| 906 |
/// } |
| 907 |
/// ``` |
| 908 |
pub fn try_send(&self, message: T) -> Result<(), TrySendError<T>> { |
| 909 |
match self.chan.semaphore().semaphore.try_acquire(1) { |
| 910 |
Ok(()) => {} |
| 911 |
Err(TryAcquireError::Closed) => return Err(TrySendError::Closed(message)), |
| 912 |
Err(TryAcquireError::NoPermits) => return Err(TrySendError::Full(message)), |
| 913 |
} |
| 914 |
|
| 915 |
// Send the message |
| 916 |
self.chan.send(message); |
| 917 |
Ok(()) |
| 918 |
} |
| 919 |
|
| 920 |
/// Sends a value, waiting until there is capacity, but only for a limited time. |
| 921 |
/// |
| 922 |
/// Shares the same success and error conditions as [`send`], adding one more |
| 923 |
/// condition for an unsuccessful send, which is when the provided timeout has |
| 924 |
/// elapsed, and there is no capacity available. |
| 925 |
/// |
| 926 |
/// [`send`]: Sender::send |
| 927 |
/// |
| 928 |
/// # Errors |
| 929 |
/// |
| 930 |
/// If the receive half of the channel is closed, either due to [`close`] |
| 931 |
/// being called or the [`Receiver`] having been dropped, |
| 932 |
/// the function returns an error. The error includes the value passed to `send`. |
| 933 |
/// |
| 934 |
/// [`close`]: Receiver::close |
| 935 |
/// [`Receiver`]: Receiver |
| 936 |
/// |
| 937 |
/// # Panics |
| 938 |
/// |
| 939 |
/// This function panics if it is called outside the context of a Tokio |
| 940 |
/// runtime [with time enabled](crate::runtime::Builder::enable_time). |
| 941 |
/// |
| 942 |
/// # Examples |
| 943 |
/// |
| 944 |
/// In the following example, each call to `send_timeout` will block until the |
| 945 |
/// previously sent value was received, unless the timeout has elapsed. |
| 946 |
/// |
| 947 |
/// ```rust |
| 948 |
/// use tokio::sync::mpsc; |
| 949 |
/// use tokio::time::{sleep, Duration}; |
| 950 |
/// |
| 951 |
/// #[tokio::main] |
| 952 |
/// async fn main() { |
| 953 |
/// let (tx, mut rx) = mpsc::channel(1); |
| 954 |
/// |
| 955 |
/// tokio::spawn(async move { |
| 956 |
/// for i in 0..10 { |
| 957 |
/// if let Err(e) = tx.send_timeout(i, Duration::from_millis(100)).await { |
| 958 |
/// println!("send error: #{:?}", e); |
| 959 |
/// return; |
| 960 |
/// } |
| 961 |
/// } |
| 962 |
/// }); |
| 963 |
/// |
| 964 |
/// while let Some(i) = rx.recv().await { |
| 965 |
/// println!("got = {}", i); |
| 966 |
/// sleep(Duration::from_millis(200)).await; |
| 967 |
/// } |
| 968 |
/// } |
| 969 |
/// ``` |
| 970 |
#[cfg(feature = "time")] |
| 971 |
#[cfg_attr(docsrs, doc(cfg(feature = "time")))] |
| 972 |
pub async fn send_timeout( |
| 973 |
&self, |
| 974 |
value: T, |
| 975 |
timeout: Duration, |
| 976 |
) -> Result<(), SendTimeoutError<T>> { |
| 977 |
let permit = match crate::time::timeout(timeout, self.reserve()).await { |
| 978 |
Err(_) => { |
| 979 |
return Err(SendTimeoutError::Timeout(value)); |
| 980 |
} |
| 981 |
Ok(Err(_)) => { |
| 982 |
return Err(SendTimeoutError::Closed(value)); |
| 983 |
} |
| 984 |
Ok(Ok(permit)) => permit, |
| 985 |
}; |
| 986 |
|
| 987 |
permit.send(value); |
| 988 |
Ok(()) |
| 989 |
} |
| 990 |
|
| 991 |
/// Blocking send to call outside of asynchronous contexts. |
| 992 |
/// |
| 993 |
/// This method is intended for use cases where you are sending from |
| 994 |
/// synchronous code to asynchronous code, and will work even if the |
| 995 |
/// receiver is not using [`blocking_recv`] to receive the message. |
| 996 |
/// |
| 997 |
/// [`blocking_recv`]: fn@crate::sync::mpsc::Receiver::blocking_recv |
| 998 |
/// |
| 999 |
/// # Panics |
| 1000 |
/// |
| 1001 |
/// This function panics if called within an asynchronous execution |
| 1002 |
/// context. |
| 1003 |
/// |
| 1004 |
/// # Examples |
| 1005 |
/// |
| 1006 |
/// ``` |
| 1007 |
/// use std::thread; |
| 1008 |
/// use tokio::runtime::Runtime; |
| 1009 |
/// use tokio::sync::mpsc; |
| 1010 |
/// |
| 1011 |
/// fn main() { |
| 1012 |
/// let (tx, mut rx) = mpsc::channel::<u8>(1); |
| 1013 |
/// |
| 1014 |
/// let sync_code = thread::spawn(move || { |
| 1015 |
/// tx.blocking_send(10).unwrap(); |
| 1016 |
/// }); |
| 1017 |
/// |
| 1018 |
/// Runtime::new().unwrap().block_on(async move { |
| 1019 |
/// assert_eq!(Some(10), rx.recv().await); |
| 1020 |
/// }); |
| 1021 |
/// sync_code.join().unwrap() |
| 1022 |
/// } |
| 1023 |
/// ``` |
| 1024 |
#[track_caller] |
| 1025 |
#[cfg(feature = "sync")] |
| 1026 |
#[cfg_attr(docsrs, doc(alias = "send_blocking"))] |
| 1027 |
pub fn blocking_send(&self, value: T) -> Result<(), SendError<T>> { |
| 1028 |
crate::future::block_on(self.send(value)) |
| 1029 |
} |
| 1030 |
|
| 1031 |
/// Checks if the channel has been closed. This happens when the |
| 1032 |
/// [`Receiver`] is dropped, or when the [`Receiver::close`] method is |
| 1033 |
/// called. |
| 1034 |
/// |
| 1035 |
/// [`Receiver`]: crate::sync::mpsc::Receiver |
| 1036 |
/// [`Receiver::close`]: crate::sync::mpsc::Receiver::close |
| 1037 |
/// |
| 1038 |
/// ``` |
| 1039 |
/// let (tx, rx) = tokio::sync::mpsc::channel::<()>(42); |
| 1040 |
/// assert!(!tx.is_closed()); |
| 1041 |
/// |
| 1042 |
/// let tx2 = tx.clone(); |
| 1043 |
/// assert!(!tx2.is_closed()); |
| 1044 |
/// |
| 1045 |
/// drop(rx); |
| 1046 |
/// assert!(tx.is_closed()); |
| 1047 |
/// assert!(tx2.is_closed()); |
| 1048 |
/// ``` |
| 1049 |
pub fn is_closed(&self) -> bool { |
| 1050 |
self.chan.is_closed() |
| 1051 |
} |
| 1052 |
|
| 1053 |
/// Waits for channel capacity. Once capacity to send one message is |
| 1054 |
/// available, it is reserved for the caller. |
| 1055 |
/// |
| 1056 |
/// If the channel is full, the function waits for the number of unreceived |
| 1057 |
/// messages to become less than the channel capacity. Capacity to send one |
| 1058 |
/// message is reserved for the caller. A [`Permit`] is returned to track |
| 1059 |
/// the reserved capacity. The [`send`] function on [`Permit`] consumes the |
| 1060 |
/// reserved capacity. |
| 1061 |
/// |
| 1062 |
/// Dropping [`Permit`] without sending a message releases the capacity back |
| 1063 |
/// to the channel. |
| 1064 |
/// |
| 1065 |
/// [`Permit`]: Permit |
| 1066 |
/// [`send`]: Permit::send |
| 1067 |
/// |
| 1068 |
/// # Cancel safety |
| 1069 |
/// |
| 1070 |
/// This channel uses a queue to ensure that calls to `send` and `reserve` |
| 1071 |
/// complete in the order they were requested. Cancelling a call to |
| 1072 |
/// `reserve` makes you lose your place in the queue. |
| 1073 |
/// |
| 1074 |
/// # Examples |
| 1075 |
/// |
| 1076 |
/// ``` |
| 1077 |
/// use tokio::sync::mpsc; |
| 1078 |
/// |
| 1079 |
/// #[tokio::main] |
| 1080 |
/// async fn main() { |
| 1081 |
/// let (tx, mut rx) = mpsc::channel(1); |
| 1082 |
/// |
| 1083 |
/// // Reserve capacity |
| 1084 |
/// let permit = tx.reserve().await.unwrap(); |
| 1085 |
/// |
| 1086 |
/// // Trying to send directly on the `tx` will fail due to no |
| 1087 |
/// // available capacity. |
| 1088 |
/// assert!(tx.try_send(123).is_err()); |
| 1089 |
/// |
| 1090 |
/// // Sending on the permit succeeds |
| 1091 |
/// permit.send(456); |
| 1092 |
/// |
| 1093 |
/// // The value sent on the permit is received |
| 1094 |
/// assert_eq!(rx.recv().await.unwrap(), 456); |
| 1095 |
/// } |
| 1096 |
/// ``` |
| 1097 |
pub async fn reserve(&self) -> Result<Permit<'_, T>, SendError<()>> { |
| 1098 |
self.reserve_inner(1).await?; |
| 1099 |
Ok(Permit { chan: &self.chan }) |
| 1100 |
} |
| 1101 |
|
| 1102 |
/// Waits for channel capacity. Once capacity to send `n` messages is |
| 1103 |
/// available, it is reserved for the caller. |
| 1104 |
/// |
| 1105 |
/// If the channel is full or if there are fewer than `n` permits available, the function waits |
| 1106 |
/// for the number of unreceived messages to become `n` less than the channel capacity. |
| 1107 |
/// Capacity to send `n` message is then reserved for the caller. |
| 1108 |
/// |
| 1109 |
/// A [`PermitIterator`] is returned to track the reserved capacity. |
| 1110 |
/// You can call this [`Iterator`] until it is exhausted to |
| 1111 |
/// get a [`Permit`] and then call [`Permit::send`]. This function is similar to |
| 1112 |
/// [`try_reserve_many`] except it awaits for the slots to become available. |
| 1113 |
/// |
| 1114 |
/// If the channel is closed, the function returns a [`SendError`]. |
| 1115 |
/// |
| 1116 |
/// Dropping [`PermitIterator`] without consuming it entirely releases the remaining |
| 1117 |
/// permits back to the channel. |
| 1118 |
/// |
| 1119 |
/// [`PermitIterator`]: PermitIterator |
| 1120 |
/// [`Permit`]: Permit |
| 1121 |
/// [`send`]: Permit::send |
| 1122 |
/// [`try_reserve_many`]: Sender::try_reserve_many |
| 1123 |
/// |
| 1124 |
/// # Cancel safety |
| 1125 |
/// |
| 1126 |
/// This channel uses a queue to ensure that calls to `send` and `reserve_many` |
| 1127 |
/// complete in the order they were requested. Cancelling a call to |
| 1128 |
/// `reserve_many` makes you lose your place in the queue. |
| 1129 |
/// |
| 1130 |
/// # Examples |
| 1131 |
/// |
| 1132 |
/// ``` |
| 1133 |
/// use tokio::sync::mpsc; |
| 1134 |
/// |
| 1135 |
/// #[tokio::main] |
| 1136 |
/// async fn main() { |
| 1137 |
/// let (tx, mut rx) = mpsc::channel(2); |
| 1138 |
/// |
| 1139 |
/// // Reserve capacity |
| 1140 |
/// let mut permit = tx.reserve_many(2).await.unwrap(); |
| 1141 |
/// |
| 1142 |
/// // Trying to send directly on the `tx` will fail due to no |
| 1143 |
/// // available capacity. |
| 1144 |
/// assert!(tx.try_send(123).is_err()); |
| 1145 |
/// |
| 1146 |
/// // Sending with the permit iterator succeeds |
| 1147 |
/// permit.next().unwrap().send(456); |
| 1148 |
/// permit.next().unwrap().send(457); |
| 1149 |
/// |
| 1150 |
/// // The iterator should now be exhausted |
| 1151 |
/// assert!(permit.next().is_none()); |
| 1152 |
/// |
| 1153 |
/// // The value sent on the permit is received |
| 1154 |
/// assert_eq!(rx.recv().await.unwrap(), 456); |
| 1155 |
/// assert_eq!(rx.recv().await.unwrap(), 457); |
| 1156 |
/// } |
| 1157 |
/// ``` |
| 1158 |
pub async fn reserve_many(&self, n: usize) -> Result<PermitIterator<'_, T>, SendError<()>> { |
| 1159 |
self.reserve_inner(n).await?; |
| 1160 |
Ok(PermitIterator { |
| 1161 |
chan: &self.chan, |
| 1162 |
n, |
| 1163 |
}) |
| 1164 |
} |
| 1165 |
|
| 1166 |
/// Waits for channel capacity, moving the `Sender` and returning an owned |
| 1167 |
/// permit. Once capacity to send one message is available, it is reserved |
| 1168 |
/// for the caller. |
| 1169 |
/// |
| 1170 |
/// This moves the sender _by value_, and returns an owned permit that can |
| 1171 |
/// be used to send a message into the channel. Unlike [`Sender::reserve`], |
| 1172 |
/// this method may be used in cases where the permit must be valid for the |
| 1173 |
/// `'static` lifetime. `Sender`s may be cloned cheaply (`Sender::clone` is |
| 1174 |
/// essentially a reference count increment, comparable to [`Arc::clone`]), |
| 1175 |
/// so when multiple [`OwnedPermit`]s are needed or the `Sender` cannot be |
| 1176 |
/// moved, it can be cloned prior to calling `reserve_owned`. |
| 1177 |
/// |
| 1178 |
/// If the channel is full, the function waits for the number of unreceived |
| 1179 |
/// messages to become less than the channel capacity. Capacity to send one |
| 1180 |
/// message is reserved for the caller. An [`OwnedPermit`] is returned to |
| 1181 |
/// track the reserved capacity. The [`send`] function on [`OwnedPermit`] |
| 1182 |
/// consumes the reserved capacity. |
| 1183 |
/// |
| 1184 |
/// Dropping the [`OwnedPermit`] without sending a message releases the |
| 1185 |
/// capacity back to the channel. |
| 1186 |
/// |
| 1187 |
/// # Cancel safety |
| 1188 |
/// |
| 1189 |
/// This channel uses a queue to ensure that calls to `send` and `reserve` |
| 1190 |
/// complete in the order they were requested. Cancelling a call to |
| 1191 |
/// `reserve_owned` makes you lose your place in the queue. |
| 1192 |
/// |
| 1193 |
/// # Examples |
| 1194 |
/// Sending a message using an [`OwnedPermit`]: |
| 1195 |
/// ``` |
| 1196 |
/// use tokio::sync::mpsc; |
| 1197 |
/// |
| 1198 |
/// #[tokio::main] |
| 1199 |
/// async fn main() { |
| 1200 |
/// let (tx, mut rx) = mpsc::channel(1); |
| 1201 |
/// |
| 1202 |
/// // Reserve capacity, moving the sender. |
| 1203 |
/// let permit = tx.reserve_owned().await.unwrap(); |
| 1204 |
/// |
| 1205 |
/// // Send a message, consuming the permit and returning |
| 1206 |
/// // the moved sender. |
| 1207 |
/// let tx = permit.send(123); |
| 1208 |
/// |
| 1209 |
/// // The value sent on the permit is received. |
| 1210 |
/// assert_eq!(rx.recv().await.unwrap(), 123); |
| 1211 |
/// |
| 1212 |
/// // The sender can now be used again. |
| 1213 |
/// tx.send(456).await.unwrap(); |
| 1214 |
/// } |
| 1215 |
/// ``` |
| 1216 |
/// |
| 1217 |
/// When multiple [`OwnedPermit`]s are needed, or the sender cannot be moved |
| 1218 |
/// by value, it can be inexpensively cloned before calling `reserve_owned`: |
| 1219 |
/// |
| 1220 |
/// ``` |
| 1221 |
/// use tokio::sync::mpsc; |
| 1222 |
/// |
| 1223 |
/// #[tokio::main] |
| 1224 |
/// async fn main() { |
| 1225 |
/// let (tx, mut rx) = mpsc::channel(1); |
| 1226 |
/// |
| 1227 |
/// // Clone the sender and reserve capacity. |
| 1228 |
/// let permit = tx.clone().reserve_owned().await.unwrap(); |
| 1229 |
/// |
| 1230 |
/// // Trying to send directly on the `tx` will fail due to no |
| 1231 |
/// // available capacity. |
| 1232 |
/// assert!(tx.try_send(123).is_err()); |
| 1233 |
/// |
| 1234 |
/// // Sending on the permit succeeds. |
| 1235 |
/// permit.send(456); |
| 1236 |
/// |
| 1237 |
/// // The value sent on the permit is received |
| 1238 |
/// assert_eq!(rx.recv().await.unwrap(), 456); |
| 1239 |
/// } |
| 1240 |
/// ``` |
| 1241 |
/// |
| 1242 |
/// [`Sender::reserve`]: Sender::reserve |
| 1243 |
/// [`OwnedPermit`]: OwnedPermit |
| 1244 |
/// [`send`]: OwnedPermit::send |
| 1245 |
/// [`Arc::clone`]: std::sync::Arc::clone |
| 1246 |
pub async fn reserve_owned(self) -> Result<OwnedPermit<T>, SendError<()>> { |
| 1247 |
self.reserve_inner(1).await?; |
| 1248 |
Ok(OwnedPermit { |
| 1249 |
chan: Some(self.chan), |
| 1250 |
}) |
| 1251 |
} |
| 1252 |
|
| 1253 |
async fn reserve_inner(&self, n: usize) -> Result<(), SendError<()>> { |
| 1254 |
crate::trace::async_trace_leaf().await; |
| 1255 |
|
| 1256 |
if n > self.max_capacity() { |
| 1257 |
return Err(SendError(())); |
| 1258 |
} |
| 1259 |
match self.chan.semaphore().semaphore.acquire(n).await { |
| 1260 |
Ok(()) => Ok(()), |
| 1261 |
Err(_) => Err(SendError(())), |
| 1262 |
} |
| 1263 |
} |
| 1264 |
|
| 1265 |
/// Tries to acquire a slot in the channel without waiting for the slot to become |
| 1266 |
/// available. |
| 1267 |
/// |
| 1268 |
/// If the channel is full this function will return [`TrySendError`], otherwise |
| 1269 |
/// if there is a slot available it will return a [`Permit`] that will then allow you |
| 1270 |
/// to [`send`] on the channel with a guaranteed slot. This function is similar to |
| 1271 |
/// [`reserve`] except it does not await for the slot to become available. |
| 1272 |
/// |
| 1273 |
/// Dropping [`Permit`] without sending a message releases the capacity back |
| 1274 |
/// to the channel. |
| 1275 |
/// |
| 1276 |
/// [`Permit`]: Permit |
| 1277 |
/// [`send`]: Permit::send |
| 1278 |
/// [`reserve`]: Sender::reserve |
| 1279 |
/// |
| 1280 |
/// # Examples |
| 1281 |
/// |
| 1282 |
/// ``` |
| 1283 |
/// use tokio::sync::mpsc; |
| 1284 |
/// |
| 1285 |
/// #[tokio::main] |
| 1286 |
/// async fn main() { |
| 1287 |
/// let (tx, mut rx) = mpsc::channel(1); |
| 1288 |
/// |
| 1289 |
/// // Reserve capacity |
| 1290 |
/// let permit = tx.try_reserve().unwrap(); |
| 1291 |
/// |
| 1292 |
/// // Trying to send directly on the `tx` will fail due to no |
| 1293 |
/// // available capacity. |
| 1294 |
/// assert!(tx.try_send(123).is_err()); |
| 1295 |
/// |
| 1296 |
/// // Trying to reserve an additional slot on the `tx` will |
| 1297 |
/// // fail because there is no capacity. |
| 1298 |
/// assert!(tx.try_reserve().is_err()); |
| 1299 |
/// |
| 1300 |
/// // Sending on the permit succeeds |
| 1301 |
/// permit.send(456); |
| 1302 |
/// |
| 1303 |
/// // The value sent on the permit is received |
| 1304 |
/// assert_eq!(rx.recv().await.unwrap(), 456); |
| 1305 |
/// |
| 1306 |
/// } |
| 1307 |
/// ``` |
| 1308 |
pub fn try_reserve(&self) -> Result<Permit<'_, T>, TrySendError<()>> { |
| 1309 |
match self.chan.semaphore().semaphore.try_acquire(1) { |
| 1310 |
Ok(()) => {} |
| 1311 |
Err(TryAcquireError::Closed) => return Err(TrySendError::Closed(())), |
| 1312 |
Err(TryAcquireError::NoPermits) => return Err(TrySendError::Full(())), |
| 1313 |
} |
| 1314 |
|
| 1315 |
Ok(Permit { chan: &self.chan }) |
| 1316 |
} |
| 1317 |
|
| 1318 |
/// Tries to acquire `n` slots in the channel without waiting for the slot to become |
| 1319 |
/// available. |
| 1320 |
/// |
| 1321 |
/// A [`PermitIterator`] is returned to track the reserved capacity. |
| 1322 |
/// You can call this [`Iterator`] until it is exhausted to |
| 1323 |
/// get a [`Permit`] and then call [`Permit::send`]. This function is similar to |
| 1324 |
/// [`reserve_many`] except it does not await for the slots to become available. |
| 1325 |
/// |
| 1326 |
/// If there are fewer than `n` permits available on the channel, then |
| 1327 |
/// this function will return a [`TrySendError::Full`]. If the channel is closed |
| 1328 |
/// this function will return a [`TrySendError::Closed`]. |
| 1329 |
/// |
| 1330 |
/// Dropping [`PermitIterator`] without consuming it entirely releases the remaining |
| 1331 |
/// permits back to the channel. |
| 1332 |
/// |
| 1333 |
/// [`PermitIterator`]: PermitIterator |
| 1334 |
/// [`send`]: Permit::send |
| 1335 |
/// [`reserve_many`]: Sender::reserve_many |
| 1336 |
/// |
| 1337 |
/// # Examples |
| 1338 |
/// |
| 1339 |
/// ``` |
| 1340 |
/// use tokio::sync::mpsc; |
| 1341 |
/// |
| 1342 |
/// #[tokio::main] |
| 1343 |
/// async fn main() { |
| 1344 |
/// let (tx, mut rx) = mpsc::channel(2); |
| 1345 |
/// |
| 1346 |
/// // Reserve capacity |
| 1347 |
/// let mut permit = tx.try_reserve_many(2).unwrap(); |
| 1348 |
/// |
| 1349 |
/// // Trying to send directly on the `tx` will fail due to no |
| 1350 |
/// // available capacity. |
| 1351 |
/// assert!(tx.try_send(123).is_err()); |
| 1352 |
/// |
| 1353 |
/// // Trying to reserve an additional slot on the `tx` will |
| 1354 |
/// // fail because there is no capacity. |
| 1355 |
/// assert!(tx.try_reserve().is_err()); |
| 1356 |
/// |
| 1357 |
/// // Sending with the permit iterator succeeds |
| 1358 |
/// permit.next().unwrap().send(456); |
| 1359 |
/// permit.next().unwrap().send(457); |
| 1360 |
/// |
| 1361 |
/// // The iterator should now be exhausted |
| 1362 |
/// assert!(permit.next().is_none()); |
| 1363 |
/// |
| 1364 |
/// // The value sent on the permit is received |
| 1365 |
/// assert_eq!(rx.recv().await.unwrap(), 456); |
| 1366 |
/// assert_eq!(rx.recv().await.unwrap(), 457); |
| 1367 |
/// |
| 1368 |
/// // Trying to call try_reserve_many with 0 will return an empty iterator |
| 1369 |
/// let mut permit = tx.try_reserve_many(0).unwrap(); |
| 1370 |
/// assert!(permit.next().is_none()); |
| 1371 |
/// |
| 1372 |
/// // Trying to call try_reserve_many with a number greater than the channel |
| 1373 |
/// // capacity will return an error |
| 1374 |
/// let permit = tx.try_reserve_many(3); |
| 1375 |
/// assert!(permit.is_err()); |
| 1376 |
/// |
| 1377 |
/// // Trying to call try_reserve_many on a closed channel will return an error |
| 1378 |
/// drop(rx); |
| 1379 |
/// let permit = tx.try_reserve_many(1); |
| 1380 |
/// assert!(permit.is_err()); |
| 1381 |
/// |
| 1382 |
/// let permit = tx.try_reserve_many(0); |
| 1383 |
/// assert!(permit.is_err()); |
| 1384 |
/// } |
| 1385 |
/// ``` |
| 1386 |
pub fn try_reserve_many(&self, n: usize) -> Result<PermitIterator<'_, T>, TrySendError<()>> { |
| 1387 |
if n > self.max_capacity() { |
| 1388 |
return Err(TrySendError::Full(())); |
| 1389 |
} |
| 1390 |
|
| 1391 |
match self.chan.semaphore().semaphore.try_acquire(n) { |
| 1392 |
Ok(()) => {} |
| 1393 |
Err(TryAcquireError::Closed) => return Err(TrySendError::Closed(())), |
| 1394 |
Err(TryAcquireError::NoPermits) => return Err(TrySendError::Full(())), |
| 1395 |
} |
| 1396 |
|
| 1397 |
Ok(PermitIterator { |
| 1398 |
chan: &self.chan, |
| 1399 |
n, |
| 1400 |
}) |
| 1401 |
} |
| 1402 |
|
| 1403 |
/// Tries to acquire a slot in the channel without waiting for the slot to become |
| 1404 |
/// available, returning an owned permit. |
| 1405 |
/// |
| 1406 |
/// This moves the sender _by value_, and returns an owned permit that can |
| 1407 |
/// be used to send a message into the channel. Unlike [`Sender::try_reserve`], |
| 1408 |
/// this method may be used in cases where the permit must be valid for the |
| 1409 |
/// `'static` lifetime. `Sender`s may be cloned cheaply (`Sender::clone` is |
| 1410 |
/// essentially a reference count increment, comparable to [`Arc::clone`]), |
| 1411 |
/// so when multiple [`OwnedPermit`]s are needed or the `Sender` cannot be |
| 1412 |
/// moved, it can be cloned prior to calling `try_reserve_owned`. |
| 1413 |
/// |
| 1414 |
/// If the channel is full this function will return a [`TrySendError`]. |
| 1415 |
/// Since the sender is taken by value, the `TrySendError` returned in this |
| 1416 |
/// case contains the sender, so that it may be used again. Otherwise, if |
| 1417 |
/// there is a slot available, this method will return an [`OwnedPermit`] |
| 1418 |
/// that can then be used to [`send`] on the channel with a guaranteed slot. |
| 1419 |
/// This function is similar to [`reserve_owned`] except it does not await |
| 1420 |
/// for the slot to become available. |
| 1421 |
/// |
| 1422 |
/// Dropping the [`OwnedPermit`] without sending a message releases the capacity back |
| 1423 |
/// to the channel. |
| 1424 |
/// |
| 1425 |
/// [`OwnedPermit`]: OwnedPermit |
| 1426 |
/// [`send`]: OwnedPermit::send |
| 1427 |
/// [`reserve_owned`]: Sender::reserve_owned |
| 1428 |
/// [`Arc::clone`]: std::sync::Arc::clone |
| 1429 |
/// |
| 1430 |
/// # Examples |
| 1431 |
/// |
| 1432 |
/// ``` |
| 1433 |
/// use tokio::sync::mpsc; |
| 1434 |
/// |
| 1435 |
/// #[tokio::main] |
| 1436 |
/// async fn main() { |
| 1437 |
/// let (tx, mut rx) = mpsc::channel(1); |
| 1438 |
/// |
| 1439 |
/// // Reserve capacity |
| 1440 |
/// let permit = tx.clone().try_reserve_owned().unwrap(); |
| 1441 |
/// |
| 1442 |
/// // Trying to send directly on the `tx` will fail due to no |
| 1443 |
/// // available capacity. |
| 1444 |
/// assert!(tx.try_send(123).is_err()); |
| 1445 |
/// |
| 1446 |
/// // Trying to reserve an additional slot on the `tx` will |
| 1447 |
/// // fail because there is no capacity. |
| 1448 |
/// assert!(tx.try_reserve().is_err()); |
| 1449 |
/// |
| 1450 |
/// // Sending on the permit succeeds |
| 1451 |
/// permit.send(456); |
| 1452 |
/// |
| 1453 |
/// // The value sent on the permit is received |
| 1454 |
/// assert_eq!(rx.recv().await.unwrap(), 456); |
| 1455 |
/// |
| 1456 |
/// } |
| 1457 |
/// ``` |
| 1458 |
pub fn try_reserve_owned(self) -> Result<OwnedPermit<T>, TrySendError<Self>> { |
| 1459 |
match self.chan.semaphore().semaphore.try_acquire(1) { |
| 1460 |
Ok(()) => {} |
| 1461 |
Err(TryAcquireError::Closed) => return Err(TrySendError::Closed(self)), |
| 1462 |
Err(TryAcquireError::NoPermits) => return Err(TrySendError::Full(self)), |
| 1463 |
} |
| 1464 |
|
| 1465 |
Ok(OwnedPermit { |
| 1466 |
chan: Some(self.chan), |
| 1467 |
}) |
| 1468 |
} |
| 1469 |
|
| 1470 |
/// Returns `true` if senders belong to the same channel. |
| 1471 |
/// |
| 1472 |
/// # Examples |
| 1473 |
/// |
| 1474 |
/// ``` |
| 1475 |
/// let (tx, rx) = tokio::sync::mpsc::channel::<()>(1); |
| 1476 |
/// let tx2 = tx.clone(); |
| 1477 |
/// assert!(tx.same_channel(&tx2)); |
| 1478 |
/// |
| 1479 |
/// let (tx3, rx3) = tokio::sync::mpsc::channel::<()>(1); |
| 1480 |
/// assert!(!tx3.same_channel(&tx2)); |
| 1481 |
/// ``` |
| 1482 |
pub fn same_channel(&self, other: &Self) -> bool { |
| 1483 |
self.chan.same_channel(&other.chan) |
| 1484 |
} |
| 1485 |
|
| 1486 |
/// Returns the current capacity of the channel. |
| 1487 |
/// |
| 1488 |
/// The capacity goes down when sending a value by calling [`send`] or by reserving capacity |
| 1489 |
/// with [`reserve`]. The capacity goes up when values are received by the [`Receiver`]. |
| 1490 |
/// This is distinct from [`max_capacity`], which always returns buffer capacity initially |
| 1491 |
/// specified when calling [`channel`] |
| 1492 |
/// |
| 1493 |
/// # Examples |
| 1494 |
/// |
| 1495 |
/// ``` |
| 1496 |
/// use tokio::sync::mpsc; |
| 1497 |
/// |
| 1498 |
/// #[tokio::main] |
| 1499 |
/// async fn main() { |
| 1500 |
/// let (tx, mut rx) = mpsc::channel::<()>(5); |
| 1501 |
/// |
| 1502 |
/// assert_eq!(tx.capacity(), 5); |
| 1503 |
/// |
| 1504 |
/// // Making a reservation drops the capacity by one. |
| 1505 |
/// let permit = tx.reserve().await.unwrap(); |
| 1506 |
/// assert_eq!(tx.capacity(), 4); |
| 1507 |
/// |
| 1508 |
/// // Sending and receiving a value increases the capacity by one. |
| 1509 |
/// permit.send(()); |
| 1510 |
/// rx.recv().await.unwrap(); |
| 1511 |
/// assert_eq!(tx.capacity(), 5); |
| 1512 |
/// } |
| 1513 |
/// ``` |
| 1514 |
/// |
| 1515 |
/// [`send`]: Sender::send |
| 1516 |
/// [`reserve`]: Sender::reserve |
| 1517 |
/// [`channel`]: channel |
| 1518 |
/// [`max_capacity`]: Sender::max_capacity |
| 1519 |
pub fn capacity(&self) -> usize { |
| 1520 |
self.chan.semaphore().semaphore.available_permits() |
| 1521 |
} |
| 1522 |
|
| 1523 |
/// Converts the `Sender` to a [`WeakSender`] that does not count |
| 1524 |
/// towards RAII semantics, i.e. if all `Sender` instances of the |
| 1525 |
/// channel were dropped and only `WeakSender` instances remain, |
| 1526 |
/// the channel is closed. |
| 1527 |
#[must_use = "Downgrade creates a WeakSender without destroying the original non-weak sender."] |
| 1528 |
pub fn downgrade(&self) -> WeakSender<T> { |
| 1529 |
WeakSender { |
| 1530 |
chan: self.chan.downgrade(), |
| 1531 |
} |
| 1532 |
} |
| 1533 |
|
| 1534 |
/// Returns the maximum buffer capacity of the channel. |
| 1535 |
/// |
| 1536 |
/// The maximum capacity is the buffer capacity initially specified when calling |
| 1537 |
/// [`channel`]. This is distinct from [`capacity`], which returns the *current* |
| 1538 |
/// available buffer capacity: as messages are sent and received, the |
| 1539 |
/// value returned by [`capacity`] will go up or down, whereas the value |
| 1540 |
/// returned by [`max_capacity`] will remain constant. |
| 1541 |
/// |
| 1542 |
/// # Examples |
| 1543 |
/// |
| 1544 |
/// ``` |
| 1545 |
/// use tokio::sync::mpsc; |
| 1546 |
/// |
| 1547 |
/// #[tokio::main] |
| 1548 |
/// async fn main() { |
| 1549 |
/// let (tx, _rx) = mpsc::channel::<()>(5); |
| 1550 |
/// |
| 1551 |
/// // both max capacity and capacity are the same at first |
| 1552 |
/// assert_eq!(tx.max_capacity(), 5); |
| 1553 |
/// assert_eq!(tx.capacity(), 5); |
| 1554 |
/// |
| 1555 |
/// // Making a reservation doesn't change the max capacity. |
| 1556 |
/// let permit = tx.reserve().await.unwrap(); |
| 1557 |
/// assert_eq!(tx.max_capacity(), 5); |
| 1558 |
/// // but drops the capacity by one |
| 1559 |
/// assert_eq!(tx.capacity(), 4); |
| 1560 |
/// } |
| 1561 |
/// ``` |
| 1562 |
/// |
| 1563 |
/// [`channel`]: channel |
| 1564 |
/// [`max_capacity`]: Sender::max_capacity |
| 1565 |
/// [`capacity`]: Sender::capacity |
| 1566 |
pub fn max_capacity(&self) -> usize { |
| 1567 |
self.chan.semaphore().bound |
| 1568 |
} |
| 1569 |
|
| 1570 |
/// Returns the number of [`Sender`] handles. |
| 1571 |
pub fn strong_count(&self) -> usize { |
| 1572 |
self.chan.strong_count() |
| 1573 |
} |
| 1574 |
|
| 1575 |
/// Returns the number of [`WeakSender`] handles. |
| 1576 |
pub fn weak_count(&self) -> usize { |
| 1577 |
self.chan.weak_count() |
| 1578 |
} |
| 1579 |
} |
| 1580 |
|
| 1581 |
impl<T> Clone for Sender<T> { |
| 1582 |
fn clone(&self) -> Self { |
| 1583 |
Sender { |
| 1584 |
chan: self.chan.clone(), |
| 1585 |
} |
| 1586 |
} |
| 1587 |
} |
| 1588 |
|
| 1589 |
impl<T> fmt::Debug for Sender<T> { |
| 1590 |
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 1591 |
fmt.debug_struct("Sender") |
| 1592 |
.field("chan", &self.chan) |
| 1593 |
.finish() |
| 1594 |
} |
| 1595 |
} |
| 1596 |
|
| 1597 |
impl<T> Clone for WeakSender<T> { |
| 1598 |
fn clone(&self) -> Self { |
| 1599 |
self.chan.increment_weak_count(); |
| 1600 |
|
| 1601 |
WeakSender { |
| 1602 |
chan: self.chan.clone(), |
| 1603 |
} |
| 1604 |
} |
| 1605 |
} |
| 1606 |
|
| 1607 |
impl<T> Drop for WeakSender<T> { |
| 1608 |
fn drop(&mut self) { |
| 1609 |
self.chan.decrement_weak_count(); |
| 1610 |
} |
| 1611 |
} |
| 1612 |
|
| 1613 |
impl<T> WeakSender<T> { |
| 1614 |
/// Tries to convert a `WeakSender` into a [`Sender`]. This will return `Some` |
| 1615 |
/// if there are other `Sender` instances alive and the channel wasn't |
| 1616 |
/// previously dropped, otherwise `None` is returned. |
| 1617 |
pub fn upgrade(&self) -> Option<Sender<T>> { |
| 1618 |
chan::Tx::upgrade(self.chan.clone()).map(Sender::new) |
| 1619 |
} |
| 1620 |
|
| 1621 |
/// Returns the number of [`Sender`] handles. |
| 1622 |
pub fn strong_count(&self) -> usize { |
| 1623 |
self.chan.strong_count() |
| 1624 |
} |
| 1625 |
|
| 1626 |
/// Returns the number of [`WeakSender`] handles. |
| 1627 |
pub fn weak_count(&self) -> usize { |
| 1628 |
self.chan.weak_count() |
| 1629 |
} |
| 1630 |
} |
| 1631 |
|
| 1632 |
impl<T> fmt::Debug for WeakSender<T> { |
| 1633 |
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 1634 |
fmt.debug_struct("WeakSender").finish() |
| 1635 |
} |
| 1636 |
} |
| 1637 |
|
| 1638 |
// ===== impl Permit ===== |
| 1639 |
|
| 1640 |
impl<T> Permit<'_, T> { |
| 1641 |
/// Sends a value using the reserved capacity. |
| 1642 |
/// |
| 1643 |
/// Capacity for the message has already been reserved. The message is sent |
| 1644 |
/// to the receiver and the permit is consumed. The operation will succeed |
| 1645 |
/// even if the receiver half has been closed. See [`Receiver::close`] for |
| 1646 |
/// more details on performing a clean shutdown. |
| 1647 |
/// |
| 1648 |
/// [`Receiver::close`]: Receiver::close |
| 1649 |
/// |
| 1650 |
/// # Examples |
| 1651 |
/// |
| 1652 |
/// ``` |
| 1653 |
/// use tokio::sync::mpsc; |
| 1654 |
/// |
| 1655 |
/// #[tokio::main] |
| 1656 |
/// async fn main() { |
| 1657 |
/// let (tx, mut rx) = mpsc::channel(1); |
| 1658 |
/// |
| 1659 |
/// // Reserve capacity |
| 1660 |
/// let permit = tx.reserve().await.unwrap(); |
| 1661 |
/// |
| 1662 |
/// // Trying to send directly on the `tx` will fail due to no |
| 1663 |
/// // available capacity. |
| 1664 |
/// assert!(tx.try_send(123).is_err()); |
| 1665 |
/// |
| 1666 |
/// // Send a message on the permit |
| 1667 |
/// permit.send(456); |
| 1668 |
/// |
| 1669 |
/// // The value sent on the permit is received |
| 1670 |
/// assert_eq!(rx.recv().await.unwrap(), 456); |
| 1671 |
/// } |
| 1672 |
/// ``` |
| 1673 |
pub fn send(self, value: T) { |
| 1674 |
use std::mem; |
| 1675 |
|
| 1676 |
self.chan.send(value); |
| 1677 |
|
| 1678 |
// Avoid the drop logic |
| 1679 |
mem::forget(self); |
| 1680 |
} |
| 1681 |
} |
| 1682 |
|
| 1683 |
impl<T> Drop for Permit<'_, T> { |
| 1684 |
fn drop(&mut self) { |
| 1685 |
use chan::Semaphore; |
| 1686 |
|
| 1687 |
let semaphore = self.chan.semaphore(); |
| 1688 |
|
| 1689 |
// Add the permit back to the semaphore |
| 1690 |
semaphore.add_permit(); |
| 1691 |
|
| 1692 |
// If this is the last sender for this channel, wake the receiver so |
| 1693 |
// that it can be notified that the channel is closed. |
| 1694 |
if semaphore.is_closed() && semaphore.is_idle() { |
| 1695 |
self.chan.wake_rx(); |
| 1696 |
} |
| 1697 |
} |
| 1698 |
} |
| 1699 |
|
| 1700 |
impl<T> fmt::Debug for Permit<'_, T> { |
| 1701 |
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 1702 |
fmt.debug_struct("Permit") |
| 1703 |
.field("chan", &self.chan) |
| 1704 |
.finish() |
| 1705 |
} |
| 1706 |
} |
| 1707 |
|
| 1708 |
// ===== impl PermitIterator ===== |
| 1709 |
|
| 1710 |
impl<'a, T> Iterator for PermitIterator<'a, T> { |
| 1711 |
type Item = Permit<'a, T>; |
| 1712 |
|
| 1713 |
fn next(&mut self) -> Option<Self::Item> { |
| 1714 |
if self.n == 0 { |
| 1715 |
return None; |
| 1716 |
} |
| 1717 |
|
| 1718 |
self.n -= 1; |
| 1719 |
Some(Permit { chan: self.chan }) |
| 1720 |
} |
| 1721 |
|
| 1722 |
fn size_hint(&self) -> (usize, Option<usize>) { |
| 1723 |
let n = self.n; |
| 1724 |
(n, Some(n)) |
| 1725 |
} |
| 1726 |
} |
| 1727 |
impl<T> ExactSizeIterator for PermitIterator<'_, T> {} |
| 1728 |
impl<T> std::iter::FusedIterator for PermitIterator<'_, T> {} |
| 1729 |
|
| 1730 |
impl<T> Drop for PermitIterator<'_, T> { |
| 1731 |
fn drop(&mut self) { |
| 1732 |
use chan::Semaphore; |
| 1733 |
|
| 1734 |
if self.n == 0 { |
| 1735 |
return; |
| 1736 |
} |
| 1737 |
|
| 1738 |
let semaphore = self.chan.semaphore(); |
| 1739 |
|
| 1740 |
// Add the remaining permits back to the semaphore |
| 1741 |
semaphore.add_permits(self.n); |
| 1742 |
|
| 1743 |
// If this is the last sender for this channel, wake the receiver so |
| 1744 |
// that it can be notified that the channel is closed. |
| 1745 |
if semaphore.is_closed() && semaphore.is_idle() { |
| 1746 |
self.chan.wake_rx(); |
| 1747 |
} |
| 1748 |
} |
| 1749 |
} |
| 1750 |
|
| 1751 |
impl<T> fmt::Debug for PermitIterator<'_, T> { |
| 1752 |
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 1753 |
fmt.debug_struct("PermitIterator") |
| 1754 |
.field("chan", &self.chan) |
| 1755 |
.field("capacity", &self.n) |
| 1756 |
.finish() |
| 1757 |
} |
| 1758 |
} |
| 1759 |
|
| 1760 |
// ===== impl Permit ===== |
| 1761 |
|
| 1762 |
impl<T> OwnedPermit<T> { |
| 1763 |
/// Sends a value using the reserved capacity. |
| 1764 |
/// |
| 1765 |
/// Capacity for the message has already been reserved. The message is sent |
| 1766 |
/// to the receiver and the permit is consumed. The operation will succeed |
| 1767 |
/// even if the receiver half has been closed. See [`Receiver::close`] for |
| 1768 |
/// more details on performing a clean shutdown. |
| 1769 |
/// |
| 1770 |
/// Unlike [`Permit::send`], this method returns the [`Sender`] from which |
| 1771 |
/// the `OwnedPermit` was reserved. |
| 1772 |
/// |
| 1773 |
/// [`Receiver::close`]: Receiver::close |
| 1774 |
/// |
| 1775 |
/// # Examples |
| 1776 |
/// |
| 1777 |
/// ``` |
| 1778 |
/// use tokio::sync::mpsc; |
| 1779 |
/// |
| 1780 |
/// #[tokio::main] |
| 1781 |
/// async fn main() { |
| 1782 |
/// let (tx, mut rx) = mpsc::channel(1); |
| 1783 |
/// |
| 1784 |
/// // Reserve capacity |
| 1785 |
/// let permit = tx.reserve_owned().await.unwrap(); |
| 1786 |
/// |
| 1787 |
/// // Send a message on the permit, returning the sender. |
| 1788 |
/// let tx = permit.send(456); |
| 1789 |
/// |
| 1790 |
/// // The value sent on the permit is received |
| 1791 |
/// assert_eq!(rx.recv().await.unwrap(), 456); |
| 1792 |
/// |
| 1793 |
/// // We may now reuse `tx` to send another message. |
| 1794 |
/// tx.send(789).await.unwrap(); |
| 1795 |
/// } |
| 1796 |
/// ``` |
| 1797 |
pub fn send(mut self, value: T) -> Sender<T> { |
| 1798 |
let chan = self.chan.take().unwrap_or_else(|| { |
| 1799 |
unreachable!("OwnedPermit channel is only taken when the permit is moved") |
| 1800 |
}); |
| 1801 |
chan.send(value); |
| 1802 |
|
| 1803 |
Sender { chan } |
| 1804 |
} |
| 1805 |
|
| 1806 |
/// Releases the reserved capacity *without* sending a message, returning the |
| 1807 |
/// [`Sender`]. |
| 1808 |
/// |
| 1809 |
/// # Examples |
| 1810 |
/// |
| 1811 |
/// ``` |
| 1812 |
/// use tokio::sync::mpsc; |
| 1813 |
/// |
| 1814 |
/// #[tokio::main] |
| 1815 |
/// async fn main() { |
| 1816 |
/// let (tx, rx) = mpsc::channel(1); |
| 1817 |
/// |
| 1818 |
/// // Clone the sender and reserve capacity |
| 1819 |
/// let permit = tx.clone().reserve_owned().await.unwrap(); |
| 1820 |
/// |
| 1821 |
/// // Trying to send on the original `tx` will fail, since the `permit` |
| 1822 |
/// // has reserved all the available capacity. |
| 1823 |
/// assert!(tx.try_send(123).is_err()); |
| 1824 |
/// |
| 1825 |
/// // Release the permit without sending a message, returning the clone |
| 1826 |
/// // of the sender. |
| 1827 |
/// let tx2 = permit.release(); |
| 1828 |
/// |
| 1829 |
/// // We may now reuse `tx` to send another message. |
| 1830 |
/// tx.send(789).await.unwrap(); |
| 1831 |
/// # drop(rx); drop(tx2); |
| 1832 |
/// } |
| 1833 |
/// ``` |
| 1834 |
/// |
| 1835 |
/// [`Sender`]: Sender |
| 1836 |
pub fn release(mut self) -> Sender<T> { |
| 1837 |
use chan::Semaphore; |
| 1838 |
|
| 1839 |
let chan = self.chan.take().unwrap_or_else(|| { |
| 1840 |
unreachable!("OwnedPermit channel is only taken when the permit is moved") |
| 1841 |
}); |
| 1842 |
|
| 1843 |
// Add the permit back to the semaphore |
| 1844 |
chan.semaphore().add_permit(); |
| 1845 |
Sender { chan } |
| 1846 |
} |
| 1847 |
} |
| 1848 |
|
| 1849 |
impl<T> Drop for OwnedPermit<T> { |
| 1850 |
fn drop(&mut self) { |
| 1851 |
use chan::Semaphore; |
| 1852 |
|
| 1853 |
// Are we still holding onto the sender? |
| 1854 |
if let Some(chan) = self.chan.take() { |
| 1855 |
let semaphore = chan.semaphore(); |
| 1856 |
|
| 1857 |
// Add the permit back to the semaphore |
| 1858 |
semaphore.add_permit(); |
| 1859 |
|
| 1860 |
// If this `OwnedPermit` is holding the last sender for this |
| 1861 |
// channel, wake the receiver so that it can be notified that the |
| 1862 |
// channel is closed. |
| 1863 |
if semaphore.is_closed() && semaphore.is_idle() { |
| 1864 |
chan.wake_rx(); |
| 1865 |
} |
| 1866 |
} |
| 1867 |
|
| 1868 |
// Otherwise, do nothing. |
| 1869 |
} |
| 1870 |
} |
| 1871 |
|
| 1872 |
impl<T> fmt::Debug for OwnedPermit<T> { |
| 1873 |
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 1874 |
fmt.debug_struct("OwnedPermit") |
| 1875 |
.field("chan", &self.chan) |
| 1876 |
.finish() |
| 1877 |
} |
| 1878 |
} |