atomic_flag.h 1.5 KB

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