one_time_event.h 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef RTC_BASE_ONE_TIME_EVENT_H_
  11. #define RTC_BASE_ONE_TIME_EVENT_H_
  12. #include "rtc_base/synchronization/mutex.h"
  13. namespace webrtc {
  14. // Provides a simple way to perform an operation (such as logging) one
  15. // time in a certain scope.
  16. // Example:
  17. // OneTimeEvent firstFrame;
  18. // ...
  19. // if (firstFrame()) {
  20. // RTC_LOG(LS_INFO) << "This is the first frame".
  21. // }
  22. class OneTimeEvent {
  23. public:
  24. OneTimeEvent() {}
  25. bool operator()() {
  26. MutexLock lock(&mutex_);
  27. if (happened_) {
  28. return false;
  29. }
  30. happened_ = true;
  31. return true;
  32. }
  33. private:
  34. bool happened_ = false;
  35. Mutex mutex_;
  36. };
  37. // A non-thread-safe, ligher-weight version of the OneTimeEvent class.
  38. class ThreadUnsafeOneTimeEvent {
  39. public:
  40. ThreadUnsafeOneTimeEvent() {}
  41. bool operator()() {
  42. if (happened_) {
  43. return false;
  44. }
  45. happened_ = true;
  46. return true;
  47. }
  48. private:
  49. bool happened_ = false;
  50. };
  51. } // namespace webrtc
  52. #endif // RTC_BASE_ONE_TIME_EVENT_H_