Skip to content

Commit b30f2a6

Browse files
ADD-SPDarksonn
andcommitted
sync: clarify the behavior of mpsc::Receiver::recv_many()
Co-authored-by: Alice Ryhl <[email protected]> Signed-off-by: ADD-SP <[email protected]>
1 parent dd74c7c commit b30f2a6

File tree

1 file changed

+28
-18
lines changed

1 file changed

+28
-18
lines changed

tokio/src/sync/mpsc/bounded.rs

Lines changed: 28 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -244,24 +244,34 @@ impl<T> Receiver<T> {
244244

245245
/// Receives the next values for this receiver and extends `buffer`.
246246
///
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.
247+
/// This method is a more efficient version of the following implementation.
248+
/// ```
249+
/// async fn recv_many(&mut self, buffer: &mut Vec<T>, limit: usize) -> usize {
250+
/// if limit == 0 {
251+
/// return 0;
252+
/// }
253+
///
254+
/// // Wait for at least one message (or channel close).
255+
/// let Some(first_message) = self.recv().await else {
256+
/// return 0;
257+
/// };
258+
///
259+
/// buffer.push(first_message);
260+
/// let mut num_pushed = 1;
261+
///
262+
/// // Try to get more messages, but don't sleep.
263+
/// while num_pushed < limit {
264+
/// if let Some(msg) = self.try_recv() {
265+
/// buffer.push(msg);
266+
/// num_pushed += 1;
267+
/// } else {
268+
/// break;
269+
/// }
270+
/// }
271+
///
272+
/// num_pushed
273+
/// }
274+
/// ```
265275
///
266276
/// # Cancel safety
267277
///

0 commit comments

Comments
 (0)