atomic_flag.h revision 645501c2ab19a559ce82a1d5a29ced159a4c30fb
1// Copyright 2016 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef MOJO_EDK_SYSTEM_ATOMIC_FLAG_H_
6#define MOJO_EDK_SYSTEM_ATOMIC_FLAG_H_
7
8#include "base/atomicops.h"
9#include "base/macros.h"
10
11namespace mojo {
12namespace edk {
13
14// AtomicFlag is a boolean flag that can be set and tested atomically. It is
15// intended to be used to fast-path checks where the common case would normally
16// release the governing mutex immediately after checking.
17//
18// Example usage:
19// void DoFoo(Bar* bar) {
20//   AutoLock l(lock_);
21//   queue_.push_back(bar);
22//   flag_.Set(true);
23// }
24//
25// void Baz() {
26//   if (!flag_)  // Assume this is the common case.
27//     return;
28//
29//   AutoLock l(lock_);
30//   ... drain queue_ ...
31//   flag_.Set(false);
32// }
33class AtomicFlag {
34 public:
35  AtomicFlag() : flag_(0) {}
36  ~AtomicFlag() {}
37
38  void Set(bool value) {
39    base::subtle::Release_Store(&flag_, value ? 1 : 0);
40  }
41
42  bool Get() const {
43    return base::subtle::Acquire_Load(&flag_) ? true : false;
44  }
45
46  operator const bool() const { return Get(); }
47
48 private:
49  base::subtle::Atomic32 flag_;
50
51  DISALLOW_COPY_AND_ASSIGN(AtomicFlag);
52};
53
54}  // namespace edk
55}  // namespace mojo
56
57#endif  // MOJO_EDK_SYSTEM_ATOMIC_FLAG_H_
58