W3cubDocs

/Rust

Function std::thread::yield_now

pub fn yield_now()

Cooperatively gives up a timeslice to the OS scheduler.

This is used when the programmer knows that the thread will have nothing to do for some time, and thus avoid wasting computing time.

For example when polling on a resource, it is common to check that it is available, and if not to yield in order to avoid busy waiting.

Thus the pattern of yielding after a failed poll is rather common when implementing low-level shared resources or synchronization primitives.

However programmers will usually prefer to use channels, Condvars, Mutexes or join for their synchronization routines, as they avoid thinking about thread scheduling.

Note that channels for example are implemented using this primitive. Indeed when you call send or recv, which are blocking, they will yield if the channel is not available.

Examples

use std::thread;

thread::yield_now();

© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.
https://doc.rust-lang.org/std/thread/fn.yield_now.html