Skip to content

Commit fb464a3

Browse files
committed
rewrote documentation for thread::yield_now()
The old documentation suggested the use of yield_now for repeated polling instead of discouraging it; it also made the false claim that channels are implementing using yield_now. (They are not, except for a corner case).
1 parent d04ec47 commit fb464a3

File tree

1 file changed

+17
-16
lines changed

1 file changed

+17
-16
lines changed

library/std/src/thread/mod.rs

+17-16
Original file line numberDiff line numberDiff line change
@@ -651,22 +651,23 @@ pub fn current() -> Thread {
651651

652652
/// Cooperatively gives up a timeslice to the OS scheduler.
653653
///
654-
/// This is used when the programmer knows that the thread will have nothing
655-
/// to do for some time, and thus avoid wasting computing time.
656-
///
657-
/// For example when polling on a resource, it is common to check that it is
658-
/// available, and if not to yield in order to avoid busy waiting.
659-
///
660-
/// Thus the pattern of `yield`ing after a failed poll is rather common when
661-
/// implementing low-level shared resources or synchronization primitives.
662-
///
663-
/// However programmers will usually prefer to use [`channel`]s, [`Condvar`]s,
664-
/// [`Mutex`]es or [`join`] for their synchronization routines, as they avoid
665-
/// thinking about thread scheduling.
666-
///
667-
/// Note that [`channel`]s for example are implemented using this primitive.
668-
/// Indeed when you call `send` or `recv`, which are blocking, they will yield
669-
/// if the channel is not available.
654+
/// This calls the underlying OS scheduler's yield primitive, signaling
655+
/// that the calling thread is willing to give up its remaining timeslice
656+
/// so that the OS may schedule other threads on the CPU.
657+
///
658+
/// A drawback of yielding in a loop is that if the OS does not have any
659+
/// other ready threads to run on the current CPU, the thread will effectively
660+
/// busy-wait, which wastes CPU time and energy.
661+
///
662+
/// Therefore, when waiting for events of interest, a programmer's first
663+
/// choice should be to use synchronization devices such as [`channel`]s,
664+
/// [`Condvar`]s, [`Mutex`]es or [`join`] since these primitives are
665+
/// implemented in a blocking manner, giving up the CPU until the event
666+
/// of interest has occurred which avoids repeated yielding.
667+
///
668+
/// `yield_now` should thus be used only rarely, mostly in situations where
669+
/// repeated polling is required because there is no other suitable way to
670+
/// learn when an event of interest has occurred.
670671
///
671672
/// # Examples
672673
///

0 commit comments

Comments
 (0)