C++ std::this_thread::yield()函数(线程抑制线程让步让出时间片)volatile
Posted Dontla
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++ std::this_thread::yield()函数(线程抑制线程让步让出时间片)volatile相关的知识,希望对你有一定的参考价值。
文章目录
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 <thread>
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 <iostream> // std::cout
#include <thread> // std::thread, std::this_thread::yield
#include <atomic> // std::atomic
std::atomic<bool> 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)
开发者涨薪指南
48位大咖的思考法则、工作方式、逻辑体系
以上是关于C++ std::this_thread::yield()函数(线程抑制线程让步让出时间片)volatile的主要内容,如果未能解决你的问题,请参考以下文章
[C++]C++入门到入土篇 HelloWorld 解析 && C++入门