Namespaces
Variants

std::this_thread:: yield

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
yield
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
定义于头文件 <thread>
void yield ( ) noexcept ;
(C++11 起)

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

目录

参数

(无)

返回值

(无)

注释

此函数的具体行为取决于实现方式,特别是所使用的操作系统调度器机制及系统状态。例如,先进先出实时调度器(Linux中的 SCHED_FIFO )会挂起当前线程并将其置于同优先级就绪线程队列的末尾,若不存在其他同优先级线程,则 yield 不产生任何效果。

示例

#include <chrono>
#include <iostream>
#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

参见

C 文档 关于 thrd_yield