Skip to content

Commit 309a9e3

Browse files
authored
Rollup merge of rust-lang#40981 - Technius:master, r=steveklabnik
Add links and some examples to std::sync::mpsc docs Addresses part of rust-lang#29377 r? @steveklabnik I took a stab at adding links to the `std::sync::mpsc` docs, and I also wrote a few examples. Edit: Whoops, typed in `?r` instead of `r?`.
2 parents 861f13c + ab4f442 commit 309a9e3

File tree

1 file changed

+172
-46
lines changed

1 file changed

+172
-46
lines changed

src/libstd/sync/mpsc/mod.rs

+172-46
Original file line numberDiff line numberDiff line change
@@ -13,40 +13,50 @@
1313
//! This module provides message-based communication over channels, concretely
1414
//! defined among three types:
1515
//!
16-
//! * `Sender`
17-
//! * `SyncSender`
18-
//! * `Receiver`
16+
//! * [`Sender`]
17+
//! * [`SyncSender`]
18+
//! * [`Receiver`]
1919
//!
20-
//! A `Sender` or `SyncSender` is used to send data to a `Receiver`. Both
20+
//! A [`Sender`] or [`SyncSender`] is used to send data to a [`Receiver`]. Both
2121
//! senders are clone-able (multi-producer) such that many threads can send
2222
//! simultaneously to one receiver (single-consumer).
2323
//!
2424
//! These channels come in two flavors:
2525
//!
26-
//! 1. An asynchronous, infinitely buffered channel. The `channel()` function
26+
//! 1. An asynchronous, infinitely buffered channel. The [`channel`] function
2727
//! will return a `(Sender, Receiver)` tuple where all sends will be
2828
//! **asynchronous** (they never block). The channel conceptually has an
2929
//! infinite buffer.
3030
//!
31-
//! 2. A synchronous, bounded channel. The `sync_channel()` function will return
32-
//! a `(SyncSender, Receiver)` tuple where the storage for pending messages
33-
//! is a pre-allocated buffer of a fixed size. All sends will be
31+
//! 2. A synchronous, bounded channel. The [`sync_channel`] function will
32+
//! return a `(SyncSender, Receiver)` tuple where the storage for pending
33+
//! messages is a pre-allocated buffer of a fixed size. All sends will be
3434
//! **synchronous** by blocking until there is buffer space available. Note
35-
//! that a bound of 0 is allowed, causing the channel to become a
36-
//! "rendezvous" channel where each sender atomically hands off a message to
37-
//! a receiver.
35+
//! that a bound of 0 is allowed, causing the channel to become a "rendezvous"
36+
//! channel where each sender atomically hands off a message to a receiver.
37+
//!
38+
//! [`Sender`]: ../../../std/sync/mpsc/struct.Sender.html
39+
//! [`SyncSender`]: ../../../std/sync/mpsc/struct.SyncSender.html
40+
//! [`Receiver`]: ../../../std/sync/mpsc/struct.Receiver.html
41+
//! [`send`]: ../../../std/sync/mpsc/struct.Sender.html#method.send
42+
//! [`channel`]: ../../../std/sync/mpsc/fn.channel.html
43+
//! [`sync_channel`]: ../../../std/sync/mpsc/fn.sync_channel.html
3844
//!
3945
//! ## Disconnection
4046
//!
41-
//! The send and receive operations on channels will all return a `Result`
47+
//! The send and receive operations on channels will all return a [`Result`]
4248
//! indicating whether the operation succeeded or not. An unsuccessful operation
4349
//! is normally indicative of the other half of a channel having "hung up" by
4450
//! being dropped in its corresponding thread.
4551
//!
4652
//! Once half of a channel has been deallocated, most operations can no longer
47-
//! continue to make progress, so `Err` will be returned. Many applications will
48-
//! continue to `unwrap()` the results returned from this module, instigating a
49-
//! propagation of failure among threads if one unexpectedly dies.
53+
//! continue to make progress, so [`Err`] will be returned. Many applications
54+
//! will continue to [`unwrap`] the results returned from this module,
55+
//! instigating a propagation of failure among threads if one unexpectedly dies.
56+
//!
57+
//! [`Result`]: ../../../std/result/enum.Result.html
58+
//! [`Err`]: ../../../std/result/enum.Result.html#variant.Err
59+
//! [`unwrap`]: ../../../std/result/enum.Result.html#method.unwrap
5060
//!
5161
//! # Examples
5262
//!
@@ -288,7 +298,31 @@ mod mpsc_queue;
288298
mod spsc_queue;
289299

290300
/// The receiving-half of Rust's channel type. This half can only be owned by
291-
/// one thread
301+
/// one thread.
302+
///
303+
/// Messages sent to the channel can be retrieved using [`recv`].
304+
///
305+
/// [`recv`]: ../../../std/sync/mpsc/struct.Receiver.html#method.recv
306+
///
307+
/// # Examples
308+
///
309+
/// ```rust
310+
/// use std::sync::mpsc::channel;
311+
/// use std::thread;
312+
/// use std::time::Duration;
313+
///
314+
/// let (send, recv) = channel();
315+
///
316+
/// thread::spawn(move || {
317+
/// send.send("Hello world!").unwrap();
318+
/// thread::sleep(Duration::from_secs(2)); // block for two seconds
319+
/// send.send("Delayed for 2 seconds").unwrap();
320+
/// });
321+
///
322+
/// println!("{}", recv.recv().unwrap()); // Received immediately
323+
/// println!("Waiting...");
324+
/// println!("{}", recv.recv().unwrap()); // Received after 2 seconds
325+
/// ```
292326
#[stable(feature = "rust1", since = "1.0.0")]
293327
pub struct Receiver<T> {
294328
inner: UnsafeCell<Flavor<T>>,
@@ -302,30 +336,39 @@ unsafe impl<T: Send> Send for Receiver<T> { }
302336
#[stable(feature = "rust1", since = "1.0.0")]
303337
impl<T> !Sync for Receiver<T> { }
304338

305-
/// An iterator over messages on a receiver, this iterator will block
306-
/// whenever `next` is called, waiting for a new message, and `None` will be
307-
/// returned when the corresponding channel has hung up.
339+
/// An iterator over messages on a receiver, this iterator will block whenever
340+
/// [`next`] is called, waiting for a new message, and [`None`] will be returned
341+
/// when the corresponding channel has hung up.
342+
///
343+
/// [`next`]: ../../../std/iter/trait.Iterator.html#tymethod.next
344+
/// [`None`]: ../../../std/option/enum.Option.html#variant.None
308345
#[stable(feature = "rust1", since = "1.0.0")]
309346
#[derive(Debug)]
310347
pub struct Iter<'a, T: 'a> {
311348
rx: &'a Receiver<T>
312349
}
313350

314351
/// An iterator that attempts to yield all pending values for a receiver.
315-
/// `None` will be returned when there are no pending values remaining or
316-
/// if the corresponding channel has hung up.
352+
/// [`None`] will be returned when there are no pending values remaining or if
353+
/// the corresponding channel has hung up.
317354
///
318355
/// This Iterator will never block the caller in order to wait for data to
319-
/// become available. Instead, it will return `None`.
356+
/// become available. Instead, it will return [`None`].
357+
///
358+
/// [`None`]: ../../../std/option/enum.Option.html#variant.None
320359
#[stable(feature = "receiver_try_iter", since = "1.15.0")]
321360
#[derive(Debug)]
322361
pub struct TryIter<'a, T: 'a> {
323362
rx: &'a Receiver<T>
324363
}
325364

326365
/// An owning iterator over messages on a receiver, this iterator will block
327-
/// whenever `next` is called, waiting for a new message, and `None` will be
366+
/// whenever [`next`] is called, waiting for a new message, and [`None`] will be
328367
/// returned when the corresponding channel has hung up.
368+
///
369+
/// [`next`]: ../../../std/iter/trait.Iterator.html#tymethod.next
370+
/// [`None`]: ../../../std/option/enum.Option.html#variant.None
371+
///
329372
#[stable(feature = "receiver_into_iter", since = "1.1.0")]
330373
#[derive(Debug)]
331374
pub struct IntoIter<T> {
@@ -334,6 +377,35 @@ pub struct IntoIter<T> {
334377

335378
/// The sending-half of Rust's asynchronous channel type. This half can only be
336379
/// owned by one thread, but it can be cloned to send to other threads.
380+
///
381+
/// Messages can be sent through this channel with [`send`].
382+
///
383+
/// [`send`]: ../../../std/sync/mpsc/struct.Sender.html#method.send
384+
///
385+
/// # Examples
386+
///
387+
/// ```rust
388+
/// use std::sync::mpsc::channel;
389+
/// use std::thread;
390+
///
391+
/// let (sender, receiver) = channel();
392+
/// let sender2 = sender.clone();
393+
///
394+
/// // First thread owns sender
395+
/// thread::spawn(move || {
396+
/// sender.send(1).unwrap();
397+
/// });
398+
///
399+
/// // Second thread owns sender2
400+
/// thread::spawn(move || {
401+
/// sender2.send(2).unwrap();
402+
/// });
403+
///
404+
/// let msg = receiver.recv().unwrap();
405+
/// let msg2 = receiver.recv().unwrap();
406+
///
407+
/// assert_eq!(3, msg + msg2);
408+
/// ```
337409
#[stable(feature = "rust1", since = "1.0.0")]
338410
pub struct Sender<T> {
339411
inner: UnsafeCell<Flavor<T>>,
@@ -349,6 +421,10 @@ impl<T> !Sync for Sender<T> { }
349421

350422
/// The sending-half of Rust's synchronous channel type. This half can only be
351423
/// owned by one thread, but it can be cloned to send to other threads.
424+
///
425+
/// [`send`]: ../../../std/sync/mpsc/struct.Sender.html#method.send
426+
/// [`SyncSender::send`]: ../../../std/sync/mpsc/struct.SyncSender.html#method.send
427+
///
352428
#[stable(feature = "rust1", since = "1.0.0")]
353429
pub struct SyncSender<T> {
354430
inner: Arc<sync::Packet<T>>,
@@ -360,25 +436,32 @@ unsafe impl<T: Send> Send for SyncSender<T> {}
360436
#[stable(feature = "rust1", since = "1.0.0")]
361437
impl<T> !Sync for SyncSender<T> {}
362438

363-
/// An error returned from the `send` function on channels.
439+
/// An error returned from the [`send`] function on channels.
364440
///
365-
/// A `send` operation can only fail if the receiving end of a channel is
441+
/// A [`send`] operation can only fail if the receiving end of a channel is
366442
/// disconnected, implying that the data could never be received. The error
367443
/// contains the data being sent as a payload so it can be recovered.
444+
///
445+
/// [`send`]: ../../../std/sync/mpsc/struct.Sender.html#method.send
368446
#[stable(feature = "rust1", since = "1.0.0")]
369447
#[derive(PartialEq, Eq, Clone, Copy)]
370448
pub struct SendError<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
371449

372-
/// An error returned from the `recv` function on a `Receiver`.
450+
/// An error returned from the [`recv`] function on a [`Receiver`].
373451
///
374-
/// The `recv` operation can only fail if the sending half of a channel is
452+
/// The [`recv`] operation can only fail if the sending half of a channel is
375453
/// disconnected, implying that no further messages will ever be received.
454+
///
455+
/// [`recv`]: ../../../std/sync/mpsc/struct.Receiver.html#method.recv
456+
/// [`Receiver`]: ../../../std/sync/mpsc/struct.Receiver.html
376457
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
377458
#[stable(feature = "rust1", since = "1.0.0")]
378459
pub struct RecvError;
379460

380-
/// This enumeration is the list of the possible reasons that `try_recv` could
461+
/// This enumeration is the list of the possible reasons that [`try_recv`] could
381462
/// not return data when called.
463+
///
464+
/// [`try_recv`]: ../../../std/sync/mpsc/struct.Receiver.html#method.try_recv
382465
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
383466
#[stable(feature = "rust1", since = "1.0.0")]
384467
pub enum TryRecvError {
@@ -393,8 +476,10 @@ pub enum TryRecvError {
393476
Disconnected,
394477
}
395478

396-
/// This enumeration is the list of possible errors that `recv_timeout` could
479+
/// This enumeration is the list of possible errors that [`recv_timeout`] could
397480
/// not return data when called.
481+
///
482+
/// [`recv_timeout`]: ../../../std/sync/mpsc/struct.Receiver.html#method.recv_timeout
398483
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
399484
#[stable(feature = "mpsc_recv_timeout", since = "1.12.0")]
400485
pub enum RecvTimeoutError {
@@ -409,7 +494,9 @@ pub enum RecvTimeoutError {
409494
}
410495

411496
/// This enumeration is the list of the possible error outcomes for the
412-
/// `SyncSender::try_send` method.
497+
/// [`SyncSender::try_send`] method.
498+
///
499+
/// [`SyncSender::try_send`]: ../../../std/sync/mpsc/struct.SyncSender.html#method.try_send
413500
#[stable(feature = "rust1", since = "1.0.0")]
414501
#[derive(PartialEq, Eq, Clone, Copy)]
415502
pub enum TrySendError<T> {
@@ -556,10 +643,13 @@ impl<T> Sender<T> {
556643
/// A successful send occurs when it is determined that the other end of
557644
/// the channel has not hung up already. An unsuccessful send would be one
558645
/// where the corresponding receiver has already been deallocated. Note
559-
/// that a return value of `Err` means that the data will never be
560-
/// received, but a return value of `Ok` does *not* mean that the data
646+
/// that a return value of [`Err`] means that the data will never be
647+
/// received, but a return value of [`Ok`] does *not* mean that the data
561648
/// will be received. It is possible for the corresponding receiver to
562-
/// hang up immediately after this function returns `Ok`.
649+
/// hang up immediately after this function returns [`Ok`].
650+
///
651+
/// [`Err`]: ../../../std/result/enum.Result.html#variant.Err
652+
/// [`Ok`]: ../../../std/result/enum.Result.html#variant.Ok
563653
///
564654
/// This method will never block the current thread.
565655
///
@@ -702,23 +792,29 @@ impl<T> SyncSender<T> {
702792
/// time. If the buffer size is 0, however, it can be guaranteed that the
703793
/// receiver has indeed received the data if this function returns success.
704794
///
705-
/// This function will never panic, but it may return `Err` if the
706-
/// `Receiver` has disconnected and is no longer able to receive
795+
/// This function will never panic, but it may return [`Err`] if the
796+
/// [`Receiver`] has disconnected and is no longer able to receive
707797
/// information.
798+
///
799+
/// [`Err`]: ../../../std/result/enum.Result.html#variant.Err
800+
/// [`Receiver`]: ../../../std/sync/mpsc/struct.Receiver.html
708801
#[stable(feature = "rust1", since = "1.0.0")]
709802
pub fn send(&self, t: T) -> Result<(), SendError<T>> {
710803
self.inner.send(t).map_err(SendError)
711804
}
712805

713806
/// Attempts to send a value on this channel without blocking.
714807
///
715-
/// This method differs from `send` by returning immediately if the
808+
/// This method differs from [`send`] by returning immediately if the
716809
/// channel's buffer is full or no receiver is waiting to acquire some
717-
/// data. Compared with `send`, this function has two failure cases
810+
/// data. Compared with [`send`], this function has two failure cases
718811
/// instead of one (one for disconnection, one for a full buffer).
719812
///
720-
/// See `SyncSender::send` for notes about guarantees of whether the
813+
/// See [`SyncSender::send`] for notes about guarantees of whether the
721814
/// receiver has received the data or not if this function is successful.
815+
///
816+
/// [`send`]: ../../../std/sync/mpsc/struct.Sender.html#method.send
817+
/// [`SyncSender::send`]: ../../../std/sync/mpsc/struct.SyncSender.html#method.send
722818
#[stable(feature = "rust1", since = "1.0.0")]
723819
pub fn try_send(&self, t: T) -> Result<(), TrySendError<T>> {
724820
self.inner.try_send(t)
@@ -819,15 +915,18 @@ impl<T> Receiver<T> {
819915
///
820916
/// This function will always block the current thread if there is no data
821917
/// available and it's possible for more data to be sent. Once a message is
822-
/// sent to the corresponding `Sender`, then this receiver will wake up and
918+
/// sent to the corresponding [`Sender`], then this receiver will wake up and
823919
/// return that message.
824920
///
825-
/// If the corresponding `Sender` has disconnected, or it disconnects while
826-
/// this call is blocking, this call will wake up and return `Err` to
921+
/// If the corresponding [`Sender`] has disconnected, or it disconnects while
922+
/// this call is blocking, this call will wake up and return [`Err`] to
827923
/// indicate that no more messages can ever be received on this channel.
828924
/// However, since channels are buffered, messages sent before the disconnect
829925
/// will still be properly received.
830926
///
927+
/// [`Sender`]: ../../../std/sync/mpsc/struct.Sender.html
928+
/// [`Err`]: ../../../std/result/enum.Result.html#variant.Err
929+
///
831930
/// # Examples
832931
///
833932
/// ```
@@ -907,15 +1006,18 @@ impl<T> Receiver<T> {
9071006
///
9081007
/// This function will always block the current thread if there is no data
9091008
/// available and it's possible for more data to be sent. Once a message is
910-
/// sent to the corresponding `Sender`, then this receiver will wake up and
1009+
/// sent to the corresponding [`Sender`], then this receiver will wake up and
9111010
/// return that message.
9121011
///
913-
/// If the corresponding `Sender` has disconnected, or it disconnects while
914-
/// this call is blocking, this call will wake up and return `Err` to
1012+
/// If the corresponding [`Sender`] has disconnected, or it disconnects while
1013+
/// this call is blocking, this call will wake up and return [`Err`] to
9151014
/// indicate that no more messages can ever be received on this channel.
9161015
/// However, since channels are buffered, messages sent before the disconnect
9171016
/// will still be properly received.
9181017
///
1018+
/// [`Sender`]: ../../../std/sync/mpsc/struct.Sender.html
1019+
/// [`Err`]: ../../../std/result/enum.Result.html#variant.Err
1020+
///
9191021
/// # Examples
9201022
///
9211023
/// ```no_run
@@ -993,16 +1095,40 @@ impl<T> Receiver<T> {
9931095
}
9941096

9951097
/// Returns an iterator that will block waiting for messages, but never
996-
/// `panic!`. It will return `None` when the channel has hung up.
1098+
/// [`panic!`]. It will return [`None`] when the channel has hung up.
1099+
///
1100+
/// [`panic!`]: ../../../std/macro.panic.html
1101+
/// [`None`]: ../../../std/option/enum.Option.html#variant.None
1102+
///
1103+
/// # Examples
1104+
///
1105+
/// ```rust
1106+
/// use std::sync::mpsc::channel;
1107+
/// use std::thread;
1108+
///
1109+
/// let (send, recv) = channel();
1110+
///
1111+
/// thread::spawn(move || {
1112+
/// send.send(1u8).unwrap();
1113+
/// send.send(2u8).unwrap();
1114+
/// send.send(3u8).unwrap();
1115+
/// });
1116+
///
1117+
/// for x in recv.iter() {
1118+
/// println!("Got: {}", x);
1119+
/// }
1120+
/// ```
9971121
#[stable(feature = "rust1", since = "1.0.0")]
9981122
pub fn iter(&self) -> Iter<T> {
9991123
Iter { rx: self }
10001124
}
10011125

10021126
/// Returns an iterator that will attempt to yield all pending values.
10031127
/// It will return `None` if there are no more pending values or if the
1004-
/// channel has hung up. The iterator will never `panic!` or block the
1128+
/// channel has hung up. The iterator will never [`panic!`] or block the
10051129
/// user by waiting for values.
1130+
///
1131+
/// [`panic!`]: ../../../std/macro.panic.html
10061132
#[stable(feature = "receiver_try_iter", since = "1.15.0")]
10071133
pub fn try_iter(&self) -> TryIter<T> {
10081134
TryIter { rx: self }

0 commit comments

Comments
 (0)