blob: 71f11b2936bc82e0d52812d833b1a0820229880b [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2012 The Chromium Authors
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
[email protected]611dbe02008-08-05 09:57:364
5#ifndef BASE_ATOMIC_SEQUENCE_NUM_H_
6#define BASE_ATOMIC_SEQUENCE_NUM_H_
7
tzikad6d8a9b2017-07-12 09:54:218#include <atomic>
9
[email protected]611dbe02008-08-05 09:57:3610namespace base {
11
tzikad6d8a9b2017-07-12 09:54:2112// 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.
[email protected]8a8443f2012-03-13 12:07:1915class AtomicSequenceNumber {
16 public:
Chris Watkins091d6292017-12-13 04:25:5817 constexpr AtomicSequenceNumber() = default;
David Bienvenub4b441e2020-09-23 05:49:5718 AtomicSequenceNumber(const AtomicSequenceNumber&) = delete;
19 AtomicSequenceNumber& operator=(const AtomicSequenceNumber&) = delete;
[email protected]8a8443f2012-03-13 12:07:1920
tzikad6d8a9b2017-07-12 09:54:2121 // Returns an increasing sequence number starts from 0 for each call.
22 // This function can be called from any thread without data race.
23 inline int GetNext() { return seq_.fetch_add(1, std::memory_order_relaxed); }
[email protected]8a8443f2012-03-13 12:07:1924
25 private:
tzikad6d8a9b2017-07-12 09:54:2126 std::atomic_int seq_{0};
[email protected]611dbe02008-08-05 09:57:3627};
28
29} // namespace base
30
31#endif // BASE_ATOMIC_SEQUENCE_NUM_H_