std::this_thread::yield(3)
β¨ std::this_thread::yield(3) β C++ Standard Libary β¨
Okay bestie, welcome to the std::this_thread::yield page from the C++ Standard Libary manual. It's giving tiny cooperative-thread moment energy, and it's honestly iconic for letting other threads breathe. π«Ά
πΈ NAME πΈ
std::this_thread::yield - std::this_thread::yield
(Yes, the name is literally the name. No notes. π )
π¦ Synopsis π¦
Defined in header <thread>
void yield() noexcept; (since C++11)
Provides a hint to the implementation to reschedule the execution of threads, allowing other threads to run. That's the whole vibe: a gentle nudge, not a command, bestie. π¦
π Parameters π
(none)β nothing to pass in, periodt.
π Return value π
(none)β it returns nothing, because it's too busy being a hint. π
π Notes π
Lowkey the exact behavior of this function depends on the implementation, in particular on the mechanics of the OS scheduler in use and the state of the system. Fr fr, it's not a universal guarantee.
For example, a first-in-first-out realtime scheduler (SCHED_FIFO in Linux) would suspend the current thread and put it on the back of the queue of the same-priority threads that are ready to run. And if there are no other threads at the same priority, yield has no effect. π
π Example π
// Run this code
#include <chrono>
#include <iostream>
#include <thread>
// "busy sleep" while suggesting that other threads run
// for a small amount of time
void little_sleep(std::chrono::microseconds us)
{
auto start = std::chrono::high_resolution_clock::now();
auto end = start + us;
do
{
std::this_thread::yield();
}
while (std::chrono::high_resolution_clock::now() < end);
}
int main()
{
auto start = std::chrono::high_resolution_clock::now();
little_sleep(std::chrono::microseconds(100));
auto elapsed = std::chrono::high_resolution_clock::now() - start;
std::cout << "waited for "
<<
std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count()
<< " microseconds\n";
}
Possible output:
waited for 128 microseconds
β See also β
- C documentation for
thrd_yield
source/version/date corner: http://cppreference.com Β· 2024.06.10 Β· page std::this_thread::yield(3) β mwah, bestie πβ¨
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms