futex_waiter.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2023 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. //
  15. #ifndef Y_ABSL_SYNCHRONIZATION_INTERNAL_FUTEX_WAITER_H_
  16. #define Y_ABSL_SYNCHRONIZATION_INTERNAL_FUTEX_WAITER_H_
  17. #include <atomic>
  18. #include <cstdint>
  19. #include "y_absl/base/config.h"
  20. #include "y_absl/synchronization/internal/kernel_timeout.h"
  21. #include "y_absl/synchronization/internal/futex.h"
  22. #include "y_absl/synchronization/internal/waiter_base.h"
  23. #ifdef Y_ABSL_INTERNAL_HAVE_FUTEX
  24. namespace y_absl {
  25. Y_ABSL_NAMESPACE_BEGIN
  26. namespace synchronization_internal {
  27. #define Y_ABSL_INTERNAL_HAVE_FUTEX_WAITER 1
  28. class FutexWaiter : public WaiterCrtp<FutexWaiter> {
  29. public:
  30. FutexWaiter() : futex_(0) {}
  31. bool Wait(KernelTimeout t);
  32. void Post();
  33. void Poke();
  34. static constexpr char kName[] = "FutexWaiter";
  35. private:
  36. // Atomically check that `*v == val`, and if it is, then sleep until the
  37. // timeout `t` has been reached, or until woken by `Wake()`.
  38. static int WaitUntil(std::atomic<int32_t>* v, int32_t val,
  39. KernelTimeout t);
  40. // Futexes are defined by specification to be 32-bits.
  41. // Thus std::atomic<int32_t> must be just an int32_t with lockfree methods.
  42. std::atomic<int32_t> futex_;
  43. static_assert(sizeof(int32_t) == sizeof(futex_), "Wrong size for futex");
  44. };
  45. } // namespace synchronization_internal
  46. Y_ABSL_NAMESPACE_END
  47. } // namespace y_absl
  48. #endif // Y_ABSL_INTERNAL_HAVE_FUTEX
  49. #endif // Y_ABSL_SYNCHRONIZATION_INTERNAL_FUTEX_WAITER_H_