개요
- 다른 스레드가 실행될 수 있도록 스케줄을 재조정
- 정확한 동작은 OS 스케줄러에 따름
- sleep은 스레드를 일시정지 시키지만 yield은 실행 대기 상태를 유지
예제
- 코드
#include <chrono>
#include <functional>
#include <iostream>
#include <thread>
using namespace std;
int main() {
const chrono::microseconds ms = chrono::microseconds(100);
auto run = [](chrono::microseconds ms, function<void()> func) {
auto start = chrono::high_resolution_clock::now();
int count = 0;
do {
++count;
func();
} while (chrono::high_resolution_clock::now() < (start + ms));
cout << count << endl;
};
run(ms, []() {});
run(ms, []() { this_thread::yield(); });
run(chrono::microseconds(0), [ms]() { this_thread::sleep_for(ms); });
return 0;
}
- 실행 결과