Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::this_thread::yield — an opportunity to reschedule

std::this_thread::yield() gives the implementation an opportunity to reschedule threads. It guarantees neither that another thread runs nor any particular waiting time, and it provides no memory synchronization.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <thread>

void std::this_thread::yield() noexcept;

// Call:
std::this_thread::yield();

std::this_thread::yield(), declared in <thread>, gives the implementation an opportunity to reschedule while the current thread is executing. It takes no arguments, returns void, and has a noexcept specification.

This is an opportunity, not a guaranteed handover of the processor to another thread. The current thread may continue immediately. Unlike std::this_thread::sleep_for, the function takes no sleep duration; it also guarantees neither fair scheduling nor completion of another thread's work.

yield() provides no synchronization: the call itself neither publishes memory writes nor makes concurrent access to shared data safe. Adding it to a loop waiting for an ordinary variable to change does not fix a data race. A separate synchronization mechanism, such as atomic operations or a mutex, is necessary.

The example makes three calls and then prints done. The bounded loop lets you check the syntax without making program completion depend on another thread. Its output does not prove that any thread switch occurred. The sources are the evolving working draft, not a frozen C++23 publication.

Examples

#include <iostream>
#include <thread>

int main() {
    for (int i = 0; i < 3; ++i) {
        std::this_thread::yield();
    }
    std::cout << "done\n";
}

Result

done

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources