atomic_flag.h 1.4 KB

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