1// Copyright (c) 2011 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 BASE_SYNCHRONIZATION_ATOMIC_FLAG_H_
6#define BASE_SYNCHRONIZATION_ATOMIC_FLAG_H_
7
8#include <stdint.h>
9
10#include <atomic>
11
12#include "base/base_export.h"
13#include "base/macros.h"
14#include "base/sequence_checker.h"
15
16namespace base {
17
18// A flag that can safely be set from one thread and read from other threads.
19//
20// This class IS NOT intended for synchronization between threads.
21class BASE_EXPORT AtomicFlag {
22 public:
23 AtomicFlag();
24 ~AtomicFlag();
25
26 // Set the flag. Must always be called from the same sequence.
27 void Set();
28
29 // Returns true iff the flag was set. If this returns true, the current thread
30 // is guaranteed to be synchronized with all memory operations on the sequence
31 // which invoked Set() up until at least the first call to Set() on it.
32 bool IsSet() const {
33 // Inline here: this has a measurable performance impact on base::WeakPtr.
34 return flag_.load(std::memory_order_acquire) != 0;
35 }
36
37 // Resets the flag. Be careful when using this: callers might not expect
38 // IsSet() to return false after returning true once.
39 void UnsafeResetForTesting();
40
41 private:
42 std::atomic<uint_fast8_t> flag_{0};
43 SEQUENCE_CHECKER(set_sequence_checker_);
44
45 DISALLOW_COPY_AND_ASSIGN(AtomicFlag);
46};
47
48} // namespace base
49
50#endif // BASE_SYNCHRONIZATION_ATOMIC_FLAG_H_
51