master
 1// -*- C++ -*-
 2//===----------------------------------------------------------------------===//
 3//
 4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
 5// See https://llvm.org/LICENSE.txt for license information.
 6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 7//
 8//===----------------------------------------------------------------------===//
 9
10#ifndef _LIBCPP___THREAD_POLL_WITH_BACKOFF_H
11#define _LIBCPP___THREAD_POLL_WITH_BACKOFF_H
12
13#include <__chrono/duration.h>
14#include <__chrono/high_resolution_clock.h>
15#include <__config>
16
17#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
18#  pragma GCC system_header
19#endif
20
21_LIBCPP_BEGIN_NAMESPACE_STD
22
23static _LIBCPP_CONSTEXPR const int __libcpp_polling_count = 64;
24
25// Polls a thread for a condition given by a predicate, and backs off based on a backoff policy
26// before polling again.
27//
28// - __poll is the "test function" that should return true if polling succeeded, and false if it failed.
29//
30// - __backoff is the "backoff policy", which is called with the duration since we started polling. It should
31//   return false in order to resume polling, and true if polling should stop entirely for some reason.
32//   In general, backoff policies sleep for some time before returning control to the polling loop.
33//
34// - __max_elapsed is the maximum duration to try polling for. If the maximum duration is exceeded,
35//   the polling loop will return false to report a timeout.
36template <class _Poll, class _Backoff>
37_LIBCPP_AVAILABILITY_SYNC _LIBCPP_HIDE_FROM_ABI bool __libcpp_thread_poll_with_backoff(
38    _Poll&& __poll, _Backoff&& __backoff, chrono::nanoseconds __max_elapsed = chrono::nanoseconds::zero()) {
39  auto const __start = chrono::high_resolution_clock::now();
40  for (int __count = 0;;) {
41    if (__poll())
42      return true; // __poll completion means success
43    if (__count < __libcpp_polling_count) {
44      __count += 1;
45      continue;
46    }
47    chrono::nanoseconds const __elapsed = chrono::high_resolution_clock::now() - __start;
48    if (__max_elapsed != chrono::nanoseconds::zero() && __max_elapsed < __elapsed)
49      return false; // timeout failure
50    if (__backoff(__elapsed))
51      return false; // __backoff completion means failure
52  }
53}
54
55// A trivial backoff policy that always immediately returns the control to
56// the polling loop.
57//
58// This is not very well-behaved since it will cause the polling loop to spin,
59// so this should most likely only be used on single-threaded systems where there
60// are no other threads to compete with.
61struct __spinning_backoff_policy {
62  _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR bool operator()(chrono::nanoseconds const&) const { return false; }
63};
64
65_LIBCPP_END_NAMESPACE_STD
66
67#endif // _LIBCPP___THREAD_POLL_WITH_BACKOFF_H