文章目录
- mancpp std::this_thread::yield
mancpp std::this_thread::yield
std::this_thread::yield(3) C++ Programmer's Manual std::this_thread::yield(3)
NAME
std::this_thread::yield - Yield to other threads
TYPE
function
SYNOPSIS
#include
void yield() noexcept;
DESCRIPTION
The calling thread yields, offering the implementation the opportunity to reschedule.
This function shall be called when a thread waits for other threads to advance without blocking.
//调用线程让步,为实现提供重新调度的机会。
//当一个线程等待其他线程无阻塞地前进时,应调用此函数。
PARAMETERS
none
RETURN VALUE
none
EXAMPLE
// this_thread::yield example
#include // std::cout
#include // std::thread, std::this_thread::yield
#include // std::atomic
std::atomic ready (false);
void count1m(int id) {
while (!ready) { // wait until main() sets ready...
std::this_thread::yield();
}
for (volatile int i=0; i<1000000; ++i) {}
std::cout << id;
}
int main ()
{
std::thread threads[10];
std::cout << "race of 10 threads that count to 1 million:n";
for (int i=0; i<10; ++i) threads[i]=std::thread(count1m,i);
ready = true; // go!
for (auto& th : threads) th.join();
std::cout << 'n';
return 0;
}
Possible output (last line may vary):
race of 10 threads that count to 1 million...
6189370542
EXCEPTION SAFETY
No-throw guarantee: never throws exceptions.
SEE ALSO
sleep_until(3)
Sleep until time point (function)
sleep_for(3)
Sleep for time span (function)
REFERENCE
cplusplus.com, 2000-2015 - All rights reserved.
cplusplus.com 2022-05-13 std::this_thread::yield(3)
(END)