notification.cc 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. #include "y_absl/synchronization/notification.h"
  15. #include <atomic>
  16. #include "y_absl/base/internal/raw_logging.h"
  17. #include "y_absl/synchronization/mutex.h"
  18. #include "y_absl/time/time.h"
  19. namespace y_absl {
  20. Y_ABSL_NAMESPACE_BEGIN
  21. void Notification::Notify() {
  22. MutexLock l(&this->mutex_);
  23. #ifndef NDEBUG
  24. if (Y_ABSL_PREDICT_FALSE(notified_yet_.load(std::memory_order_relaxed))) {
  25. Y_ABSL_RAW_LOG(
  26. FATAL,
  27. "Notify() method called more than once for Notification object %p",
  28. static_cast<void *>(this));
  29. }
  30. #endif
  31. notified_yet_.store(true, std::memory_order_release);
  32. }
  33. Notification::~Notification() {
  34. // Make sure that the thread running Notify() exits before the object is
  35. // destructed.
  36. MutexLock l(&this->mutex_);
  37. }
  38. void Notification::WaitForNotification() const {
  39. if (!HasBeenNotifiedInternal(&this->notified_yet_)) {
  40. this->mutex_.LockWhen(Condition(&HasBeenNotifiedInternal,
  41. &this->notified_yet_));
  42. this->mutex_.Unlock();
  43. }
  44. }
  45. bool Notification::WaitForNotificationWithTimeout(
  46. y_absl::Duration timeout) const {
  47. bool notified = HasBeenNotifiedInternal(&this->notified_yet_);
  48. if (!notified) {
  49. notified = this->mutex_.LockWhenWithTimeout(
  50. Condition(&HasBeenNotifiedInternal, &this->notified_yet_), timeout);
  51. this->mutex_.Unlock();
  52. }
  53. return notified;
  54. }
  55. bool Notification::WaitForNotificationWithDeadline(y_absl::Time deadline) const {
  56. bool notified = HasBeenNotifiedInternal(&this->notified_yet_);
  57. if (!notified) {
  58. notified = this->mutex_.LockWhenWithDeadline(
  59. Condition(&HasBeenNotifiedInternal, &this->notified_yet_), deadline);
  60. this->mutex_.Unlock();
  61. }
  62. return notified;
  63. }
  64. Y_ABSL_NAMESPACE_END
  65. } // namespace y_absl