notification.cc 2.3 KB

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