std::this_thread::yield

定义于头文件 <thread>
void yield() noexcept;
(C++11 起)

提供提示给实现,以重调度线程的执行,允许其他线程运行。

目录

参数

(无)

返回值

(无)

注意

此函数的准确性为依赖于实现,特别是使用中的 OS 调度器机制和系统状态。例如,先进先出实时调度器( Linux 的 SCHED_FIFO )将悬挂当前线程并将它放到准备运行的同优先级线程的队列尾(而若无其他线程在同优先级,则 yield 无效果)。

示例

#include <iostream>
#include <chrono>
#include <thread>
 
// 建议其他线程运行一小段时间的“忙睡眠”
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";
}

可能的输出:

waited for 128 microseconds

参阅

thrd_yieldC 文档

版本历史

  • (当前 | 先前 2017年8月25日 (五) 01:06Fruderica讨论 | 贡献. . (1,519字节) (+79). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 18:11P12bot讨论 | 贡献 . . (1,440字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 17:38P12bot讨论 | 贡献 . . (1,440字节) (+193). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月27日 (六) 11:35P12讨论 | 贡献 . . (1,247字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (1,247字节) (-37). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 03:32P12讨论 | 贡献 . . (1,284字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (1,284字节) (+1,284). . (Translated from the English version using Google Translate)