diff options
Diffstat (limited to 'src/common/polyfill_thread.h')
| -rw-r--r-- | src/common/polyfill_thread.h | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/src/common/polyfill_thread.h b/src/common/polyfill_thread.h index 5a8d1ce08..b2c929d2f 100644 --- a/src/common/polyfill_thread.h +++ b/src/common/polyfill_thread.h | |||
| @@ -11,6 +11,8 @@ | |||
| 11 | 11 | ||
| 12 | #ifdef __cpp_lib_jthread | 12 | #ifdef __cpp_lib_jthread |
| 13 | 13 | ||
| 14 | #include <chrono> | ||
| 15 | #include <condition_variable> | ||
| 14 | #include <stop_token> | 16 | #include <stop_token> |
| 15 | #include <thread> | 17 | #include <thread> |
| 16 | 18 | ||
| @@ -21,11 +23,23 @@ void CondvarWait(Condvar& cv, Lock& lock, std::stop_token token, Pred&& pred) { | |||
| 21 | cv.wait(lock, token, std::move(pred)); | 23 | cv.wait(lock, token, std::move(pred)); |
| 22 | } | 24 | } |
| 23 | 25 | ||
| 26 | template <typename Rep, typename Period> | ||
| 27 | bool StoppableTimedWait(std::stop_token token, const std::chrono::duration<Rep, Period>& rel_time) { | ||
| 28 | std::condition_variable_any cv; | ||
| 29 | std::mutex m; | ||
| 30 | |||
| 31 | // Perform the timed wait. | ||
| 32 | std::unique_lock lk{m}; | ||
| 33 | return !cv.wait_for(lk, token, rel_time, [&] { return token.stop_requested(); }); | ||
| 34 | } | ||
| 35 | |||
| 24 | } // namespace Common | 36 | } // namespace Common |
| 25 | 37 | ||
| 26 | #else | 38 | #else |
| 27 | 39 | ||
| 28 | #include <atomic> | 40 | #include <atomic> |
| 41 | #include <chrono> | ||
| 42 | #include <condition_variable> | ||
| 29 | #include <functional> | 43 | #include <functional> |
| 30 | #include <list> | 44 | #include <list> |
| 31 | #include <memory> | 45 | #include <memory> |
| @@ -318,6 +332,28 @@ void CondvarWait(Condvar& cv, Lock& lock, std::stop_token token, Pred pred) { | |||
| 318 | cv.wait(lock, [&] { return pred() || token.stop_requested(); }); | 332 | cv.wait(lock, [&] { return pred() || token.stop_requested(); }); |
| 319 | } | 333 | } |
| 320 | 334 | ||
| 335 | template <typename Rep, typename Period> | ||
| 336 | bool StoppableTimedWait(std::stop_token token, const std::chrono::duration<Rep, Period>& rel_time) { | ||
| 337 | if (token.stop_requested()) { | ||
| 338 | return false; | ||
| 339 | } | ||
| 340 | |||
| 341 | bool stop_requested = false; | ||
| 342 | std::condition_variable cv; | ||
| 343 | std::mutex m; | ||
| 344 | |||
| 345 | std::stop_callback cb(token, [&] { | ||
| 346 | // Wake up the waiting thread. | ||
| 347 | std::unique_lock lk{m}; | ||
| 348 | stop_requested = true; | ||
| 349 | cv.notify_one(); | ||
| 350 | }); | ||
| 351 | |||
| 352 | // Perform the timed wait. | ||
| 353 | std::unique_lock lk{m}; | ||
| 354 | return !cv.wait_for(lk, rel_time, [&] { return stop_requested; }); | ||
| 355 | } | ||
| 356 | |||
| 321 | } // namespace Common | 357 | } // namespace Common |
| 322 | 358 | ||
| 323 | #endif | 359 | #endif |