atomic_sequence_num.h 1.0 KB

12345678910111213141516171819202122232425262728293031
  1. // Copyright (c) 2012 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_ATOMIC_SEQUENCE_NUM_H_
  5. #define BASE_ATOMIC_SEQUENCE_NUM_H_
  6. #include <atomic>
  7. namespace base {
  8. // AtomicSequenceNumber is a thread safe increasing sequence number generator.
  9. // Its constructor doesn't emit a static initializer, so it's safe to use as a
  10. // global variable or static member.
  11. class AtomicSequenceNumber {
  12. public:
  13. constexpr AtomicSequenceNumber() = default;
  14. AtomicSequenceNumber(const AtomicSequenceNumber&) = delete;
  15. AtomicSequenceNumber& operator=(const AtomicSequenceNumber&) = delete;
  16. // Returns an increasing sequence number starts from 0 for each call.
  17. // This function can be called from any thread without data race.
  18. inline int GetNext() { return seq_.fetch_add(1, std::memory_order_relaxed); }
  19. private:
  20. std::atomic_int seq_{0};
  21. };
  22. } // namespace base
  23. #endif // BASE_ATOMIC_SEQUENCE_NUM_H_