N 秒間だけ処理を実行する c++ のコード
処理を実行するのは、メインスレッドでない別のスレッド。
メインスレッドは、sleep_for
で待機して、時間になったら atomic_bool
で通知する。
#include "bits/stdc++.h" using namespace std; int main(){ atomic_bool halt(false); long long counter = 0; thread t([&halt, &counter](){ while (!halt){ ++counter; } }); this_thread::sleep_for(chrono::seconds(1)); halt = true; t.join(); cout << "counter: " << counter << endl; return 0; }
若干遠回りの方法だけれども、むしろこっちの方が有利な点もあるかと思う。
std::chrono::system_clock
がボトルネックになる場合は使えるかも。