skvlad | 98bb664 | 2016-04-07 22:36:45 | [diff] [blame] | 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 | |
Steve Anton | 10542f2 | 2019-01-11 17:11:00 | [diff] [blame] | 11 | #ifndef RTC_BASE_ONE_TIME_EVENT_H_ |
| 12 | #define RTC_BASE_ONE_TIME_EVENT_H_ |
skvlad | 98bb664 | 2016-04-07 22:36:45 | [diff] [blame] | 13 | |
Markus Handell | 18523c3 | 2020-07-08 15:55:58 | [diff] [blame] | 14 | #include "rtc_base/synchronization/mutex.h" |
skvlad | 98bb664 | 2016-04-07 22:36:45 | [diff] [blame] | 15 | |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 16 | namespace webrtc { |
| 17 | // Provides a simple way to perform an operation (such as logging) one |
| 18 | // time in a certain scope. |
| 19 | // Example: |
| 20 | // OneTimeEvent firstFrame; |
| 21 | // ... |
| 22 | // if (firstFrame()) { |
Mirko Bonadei | 675513b | 2017-11-09 10:09:25 | [diff] [blame] | 23 | // RTC_LOG(LS_INFO) << "This is the first frame". |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 24 | // } |
| 25 | class OneTimeEvent { |
| 26 | public: |
| 27 | OneTimeEvent() {} |
| 28 | bool operator()() { |
Markus Handell | 18523c3 | 2020-07-08 15:55:58 | [diff] [blame] | 29 | MutexLock lock(&mutex_); |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 30 | if (happened_) { |
| 31 | return false; |
| 32 | } |
| 33 | happened_ = true; |
| 34 | return true; |
| 35 | } |
| 36 | |
| 37 | private: |
| 38 | bool happened_ = false; |
Markus Handell | 18523c3 | 2020-07-08 15:55:58 | [diff] [blame] | 39 | Mutex mutex_; |
Henrik Kjellander | ec78f1c | 2017-06-29 05:52:50 | [diff] [blame] | 40 | }; |
| 41 | |
| 42 | // A non-thread-safe, ligher-weight version of the OneTimeEvent class. |
| 43 | class ThreadUnsafeOneTimeEvent { |
| 44 | public: |
| 45 | ThreadUnsafeOneTimeEvent() {} |
| 46 | bool operator()() { |
| 47 | if (happened_) { |
| 48 | return false; |
| 49 | } |
| 50 | happened_ = true; |
| 51 | return true; |
| 52 | } |
| 53 | |
| 54 | private: |
| 55 | bool happened_ = false; |
| 56 | }; |
| 57 | |
| 58 | } // namespace webrtc |
skvlad | 98bb664 | 2016-04-07 22:36:45 | [diff] [blame] | 59 | |
Steve Anton | 10542f2 | 2019-01-11 17:11:00 | [diff] [blame] | 60 | #endif // RTC_BASE_ONE_TIME_EVENT_H_ |