blob: 8c55e2672d773d59e152c5dcfef625efa2aa172d [file] [log] [blame]
skvlad98bb6642016-04-07 15:36:45 -07001/*
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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#ifndef RTC_BASE_ONETIMEEVENT_H_
12#define RTC_BASE_ONETIMEEVENT_H_
skvlad98bb6642016-04-07 15:36:45 -070013
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020014#include "rtc_base/criticalsection.h"
Mirko Bonadei71207422017-09-15 13:58:09 +020015#include "typedefs.h" // NOLINT(build/include)
skvlad98bb6642016-04-07 15:36:45 -070016
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020017namespace webrtc {
18// Provides a simple way to perform an operation (such as logging) one
19// time in a certain scope.
20// Example:
21// OneTimeEvent firstFrame;
22// ...
23// if (firstFrame()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +010024// RTC_LOG(LS_INFO) << "This is the first frame".
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020025// }
26class OneTimeEvent {
27 public:
28 OneTimeEvent() {}
29 bool operator()() {
30 rtc::CritScope cs(&critsect_);
31 if (happened_) {
32 return false;
33 }
34 happened_ = true;
35 return true;
36 }
37
38 private:
39 bool happened_ = false;
40 rtc::CriticalSection critsect_;
41};
42
43// A non-thread-safe, ligher-weight version of the OneTimeEvent class.
44class ThreadUnsafeOneTimeEvent {
45 public:
46 ThreadUnsafeOneTimeEvent() {}
47 bool operator()() {
48 if (happened_) {
49 return false;
50 }
51 happened_ = true;
52 return true;
53 }
54
55 private:
56 bool happened_ = false;
57};
58
59} // namespace webrtc
skvlad98bb6642016-04-07 15:36:45 -070060
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020061#endif // RTC_BASE_ONETIMEEVENT_H_