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以降)

スレッドの実行を再スケジュールし、他のスレッドが実行できるようにする実装へのヒントを提供します。

目次

パラメータ

(なし)

戻り値

(なし)

注記

この関数の正確な動作は実装に依存します。特に、使用中のOSスケジューラの仕組みとシステムの状態によって異なります。例えば、FIFO(先入れ先出し)リアルタイムスケジューラ(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