kernel_timeout.h 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #ifndef Y_ABSL_SYNCHRONIZATION_INTERNAL_KERNEL_TIMEOUT_H_
  15. #define Y_ABSL_SYNCHRONIZATION_INTERNAL_KERNEL_TIMEOUT_H_
  16. #ifndef _WIN32
  17. #include <sys/types.h>
  18. #endif
  19. #include <algorithm>
  20. #include <chrono> // NOLINT(build/c++11)
  21. #include <cstdint>
  22. #include <ctime>
  23. #include <limits>
  24. #include "y_absl/base/config.h"
  25. #include "y_absl/base/internal/raw_logging.h"
  26. #include "y_absl/time/clock.h"
  27. #include "y_absl/time/time.h"
  28. namespace y_absl {
  29. Y_ABSL_NAMESPACE_BEGIN
  30. namespace synchronization_internal {
  31. // An optional timeout, with nanosecond granularity.
  32. //
  33. // This is a private low-level API for use by a handful of low-level
  34. // components. Higher-level components should build APIs based on
  35. // y_absl::Time and y_absl::Duration.
  36. class KernelTimeout {
  37. public:
  38. // Construct an absolute timeout that should expire at `t`.
  39. explicit KernelTimeout(y_absl::Time t);
  40. // Construct a relative timeout that should expire after `d`.
  41. explicit KernelTimeout(y_absl::Duration d);
  42. // Infinite timeout.
  43. constexpr KernelTimeout() : rep_(kNoTimeout) {}
  44. // A more explicit factory for those who prefer it.
  45. // Equivalent to `KernelTimeout()`.
  46. static constexpr KernelTimeout Never() { return KernelTimeout(); }
  47. // Returns true if there is a timeout that will eventually expire.
  48. // Returns false if the timeout is infinite.
  49. bool has_timeout() const { return rep_ != kNoTimeout; }
  50. // If `has_timeout()` is true, returns true if the timeout was provided as an
  51. // `y_absl::Time`. The return value is undefined if `has_timeout()` is false
  52. // because all indefinite timeouts are equivalent.
  53. bool is_absolute_timeout() const { return (rep_ & 1) == 0; }
  54. // If `has_timeout()` is true, returns true if the timeout was provided as an
  55. // `y_absl::Duration`. The return value is undefined if `has_timeout()` is false
  56. // because all indefinite timeouts are equivalent.
  57. bool is_relative_timeout() const { return (rep_ & 1) == 1; }
  58. // Convert to `struct timespec` for interfaces that expect an absolute
  59. // timeout. If !has_timeout() or is_relative_timeout(), attempts to convert to
  60. // a reasonable absolute timeout, but callers should to test has_timeout() and
  61. // is_relative_timeout() and prefer to use a more appropriate interface.
  62. struct timespec MakeAbsTimespec() const;
  63. // Convert to `struct timespec` for interfaces that expect a relative
  64. // timeout. If !has_timeout() or is_absolute_timeout(), attempts to convert to
  65. // a reasonable relative timeout, but callers should to test has_timeout() and
  66. // is_absolute_timeout() and prefer to use a more appropriate interface. Since
  67. // the return value is a relative duration, it should be recomputed by calling
  68. // this method in the case of a spurious wakeup.
  69. struct timespec MakeRelativeTimespec() const;
  70. #ifndef _WIN32
  71. // Convert to `struct timespec` for interfaces that expect an absolute timeout
  72. // on a specific clock `c`. This is similar to `MakeAbsTimespec()`, but
  73. // callers usually want to use this method with `CLOCK_MONOTONIC` when
  74. // relative timeouts are requested, and when the appropriate interface expects
  75. // an absolute timeout relative to a specific clock (for example,
  76. // pthread_cond_clockwait() or sem_clockwait()). If !has_timeout(), attempts
  77. // to convert to a reasonable absolute timeout, but callers should to test
  78. // has_timeout() prefer to use a more appropriate interface.
  79. struct timespec MakeClockAbsoluteTimespec(clockid_t c) const;
  80. #endif
  81. // Convert to unix epoch nanos for interfaces that expect an absolute timeout
  82. // in nanoseconds. If !has_timeout() or is_relative_timeout(), attempts to
  83. // convert to a reasonable absolute timeout, but callers should to test
  84. // has_timeout() and is_relative_timeout() and prefer to use a more
  85. // appropriate interface.
  86. int64_t MakeAbsNanos() const;
  87. // Converts to milliseconds from now, or INFINITE when
  88. // !has_timeout(). For use by SleepConditionVariableSRW on
  89. // Windows. Callers should recognize that the return value is a
  90. // relative duration (it should be recomputed by calling this method
  91. // in the case of a spurious wakeup).
  92. // This header file may be included transitively by public header files,
  93. // so we define our own DWORD and INFINITE instead of getting them from
  94. // <intsafe.h> and <WinBase.h>.
  95. typedef unsigned long DWord; // NOLINT
  96. DWord InMillisecondsFromNow() const;
  97. // Convert to std::chrono::time_point for interfaces that expect an absolute
  98. // timeout, like std::condition_variable::wait_until(). If !has_timeout() or
  99. // is_relative_timeout(), attempts to convert to a reasonable absolute
  100. // timeout, but callers should test has_timeout() and is_relative_timeout()
  101. // and prefer to use a more appropriate interface.
  102. std::chrono::time_point<std::chrono::system_clock> ToChronoTimePoint() const;
  103. // Convert to std::chrono::time_point for interfaces that expect a relative
  104. // timeout, like std::condition_variable::wait_for(). If !has_timeout() or
  105. // is_absolute_timeout(), attempts to convert to a reasonable relative
  106. // timeout, but callers should test has_timeout() and is_absolute_timeout()
  107. // and prefer to use a more appropriate interface. Since the return value is a
  108. // relative duration, it should be recomputed by calling this method in the
  109. // case of a spurious wakeup.
  110. std::chrono::nanoseconds ToChronoDuration() const;
  111. // Returns true if steady (aka monotonic) clocks are supported by the system.
  112. // This method exists because go/btm requires synchronized clocks, and
  113. // thus requires we use the system (aka walltime) clock.
  114. static constexpr bool SupportsSteadyClock() { return true; }
  115. private:
  116. // Returns the current time, expressed as a count of nanoseconds since the
  117. // epoch used by an arbitrary clock. The implementation tries to use a steady
  118. // (monotonic) clock if one is available.
  119. static int64_t SteadyClockNow();
  120. // Internal representation.
  121. // - If the value is kNoTimeout, then the timeout is infinite, and
  122. // has_timeout() will return true.
  123. // - If the low bit is 0, then the high 63 bits is the number of nanoseconds
  124. // after the unix epoch.
  125. // - If the low bit is 1, then the high 63 bits is the number of nanoseconds
  126. // after the epoch used by SteadyClockNow().
  127. //
  128. // In all cases the time is stored as an absolute time, the only difference is
  129. // the clock epoch. The use of absolute times is important since in the case
  130. // of a relative timeout with a spurious wakeup, the program would have to
  131. // restart the wait, and thus needs a way of recomputing the remaining time.
  132. uint64_t rep_;
  133. // Returns the number of nanoseconds stored in the internal representation.
  134. // When combined with the clock epoch indicated by the low bit (which is
  135. // accessed through is_absolute_timeout() and is_relative_timeout()), the
  136. // return value is used to compute when the timeout should occur.
  137. int64_t RawAbsNanos() const { return static_cast<int64_t>(rep_ >> 1); }
  138. // Converts to nanoseconds from now. Since the return value is a relative
  139. // duration, it should be recomputed by calling this method in the case of a
  140. // spurious wakeup.
  141. int64_t InNanosecondsFromNow() const;
  142. // A value that represents no timeout (or an infinite timeout).
  143. static constexpr uint64_t kNoTimeout = (std::numeric_limits<uint64_t>::max)();
  144. // The maximum value that can be stored in the high 63 bits.
  145. static constexpr int64_t kMaxNanos = (std::numeric_limits<int64_t>::max)();
  146. };
  147. } // namespace synchronization_internal
  148. Y_ABSL_NAMESPACE_END
  149. } // namespace y_absl
  150. #endif // Y_ABSL_SYNCHRONIZATION_INTERNAL_KERNEL_TIMEOUT_H_