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