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 스케줄러의 메커니즘과 시스템 상태에 영향을 받습니다. 예를 들어, 선입선출 실시간 스케줄러( 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 문서 for thrd_yield