• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
11 namespace mojo {
12 namespace 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 // }
33 class AtomicFlag {
34  public:
AtomicFlag()35   AtomicFlag() : flag_(0) {}
~AtomicFlag()36   ~AtomicFlag() {}
37 
Set(bool value)38   void Set(bool value) {
39     base::subtle::Release_Store(&flag_, value ? 1 : 0);
40   }
41 
Get()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