Skip to content

Commit c5ce0e6

Browse files
committed
Auto merge of #41982 - gamazeps:thread-yield-now, r=GuillaumeGomez
[Doc] Explain why `thread::yield_now` could be used. Part of #29378. r? @steveklabnik
2 parents 9f15631 + a9cb094 commit c5ce0e6

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/libstd/thread/mod.rs

+23
Original file line numberDiff line numberDiff line change
@@ -468,13 +468,36 @@ pub fn current() -> Thread {
468468

469469
/// Cooperatively gives up a timeslice to the OS scheduler.
470470
///
471+
/// This is used when the programmer knows that the thread will have nothing
472+
/// to do for some time, and thus avoid wasting computing time.
473+
///
474+
/// For example when polling on a resource, it is common to check that it is
475+
/// available, and if not to yield in order to avoid busy waiting.
476+
///
477+
/// Thus the pattern of `yield`ing after a failed poll is rather common when
478+
/// implementing low-level shared resources or synchronization primitives.
479+
///
480+
/// However programmers will usualy prefer to use, [`channel`]s, [`Condvar`]s,
481+
/// [`Mutex`]es or [`join`] for their synchronisation routines, as they avoid
482+
/// thinking about thread schedulling.
483+
///
484+
/// Note that [`channel`]s for example are implemented using this primitive.
485+
/// Indeed when you call `send` or `recv`, which are blocking, they will yield
486+
/// if the channel is not available.
487+
///
471488
/// # Examples
472489
///
473490
/// ```
474491
/// use std::thread;
475492
///
476493
/// thread::yield_now();
477494
/// ```
495+
///
496+
/// [`channel`]: ../../std/sync/mpsc/index.html
497+
/// [`spawn`]: ../../std/thread/fn.spawn.html
498+
/// [`join`]: ../../std/thread/struct.JoinHandle.html#method.join
499+
/// [`Mutex`]: ../../std/sync/struct.Mutex.html
500+
/// [`Condvar`]: ../../std/sync/struct.Condvar.html
478501
#[stable(feature = "rust1", since = "1.0.0")]
479502
pub fn yield_now() {
480503
imp::Thread::yield_now()

0 commit comments

Comments
 (0)