atomic_sequence_num.h 960 B

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