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_CORE_ATOMIC_FLAG_H_ 6 #define MOJO_CORE_ATOMIC_FLAG_H_ 7 8 #include "base/atomicops.h" 9 #include "base/macros.h" 10 11 namespace mojo { 12 namespace core { 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) { base::subtle::Release_Store(&flag_, value ? 1 : 0); } 39 Get()40 bool Get() const { return base::subtle::Acquire_Load(&flag_) ? true : false; } 41 42 operator const bool() const { return Get(); } 43 44 private: 45 base::subtle::Atomic32 flag_; 46 47 DISALLOW_COPY_AND_ASSIGN(AtomicFlag); 48 }; 49 50 } // namespace core 51 } // namespace mojo 52 53 #endif // MOJO_CORE_ATOMIC_FLAG_H_ 54