C++ の thread ライブラリの yield を使って実行権限を譲渡 ― 2020年10月08日 11時22分38秒
yeild を使うと実行権を渡すだけなので、他のスレッドとの確実な同期は取れないが、今回は例なので。メインスレッドは一秒間休止した後に広域変数を true に変えている。サブスレッドはメインスレッドがこの値を変更するまで yield し続ける。
% cat thread_yield.cpp
#include <thread>
#include <chrono>
#include <iostream>
bool ready = false;
void wait()
{
int c;
while( ! ready )
{
++c;
std::this_thread::yield();
}
std::cout << "SUB yield " << c << " times" << std::e
ndl;
}
int main()
{
std::thread t( wait );
std::this_thread::sleep_for( std::chrono::seconds( 1 ) );
ready = true;
t.join();
}
コンパイルして実行した結果。スレッドライブラリを使うので -lptherad が必要になる。
なお、実行結果はプログラムを走らせる度に変わる。一秒の間に随分とコンテキストスイッチを行った。
% c++ -std=c++11 thread_yield.cpp -lpthread
% ./a.out
SUB yield 545018947 times
最近のコメント