blob: f649f15ded72b5ee23d42ae762c9690f57d31104 [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"
skvlad98bb6642016-04-07 15:36:45 -070015
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020016namespace 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 Bonadei675513b2017-11-09 11:09:25 +010023// RTC_LOG(LS_INFO) << "This is the first frame".
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020024// }
25class OneTimeEvent {
26 public:
27 OneTimeEvent() {}
28 bool operator()() {
29 rtc::CritScope cs(&critsect_);
30 if (happened_) {
31 return false;
32 }
33 happened_ = true;
34 return true;
35 }
36
37 private:
38 bool happened_ = false;
39 rtc::CriticalSection critsect_;
40};
41
42// A non-thread-safe, ligher-weight version of the OneTimeEvent class.
43class 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
skvlad98bb6642016-04-07 15:36:45 -070059
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020060#endif // RTC_BASE_ONETIMEEVENT_H_