[email protected] | 8a8443f | 2012-03-13 12:07:19 | [diff] [blame] | 1 | // Copyright (c) 2012 The Chromium Authors. All rights reserved. |
license.bot | bf09a50 | 2008-08-24 00:55:55 | [diff] [blame] | 2 | // Use of this source code is governed by a BSD-style license that can be |
3 | // found in the LICENSE file. | ||||
[email protected] | 611dbe0 | 2008-08-05 09:57:36 | [diff] [blame] | 4 | |
5 | #ifndef BASE_ATOMIC_SEQUENCE_NUM_H_ | ||||
6 | #define BASE_ATOMIC_SEQUENCE_NUM_H_ | ||||
7 | |||||
tzik | ad6d8a9b | 2017-07-12 09:54:21 | [diff] [blame^] | 8 | #include <atomic> |
9 | |||||
avi | 9b6f4293 | 2015-12-26 22:15:14 | [diff] [blame] | 10 | #include "base/macros.h" |
[email protected] | 611dbe0 | 2008-08-05 09:57:36 | [diff] [blame] | 11 | |
12 | namespace base { | ||||
13 | |||||
tzik | ad6d8a9b | 2017-07-12 09:54:21 | [diff] [blame^] | 14 | // AtomicSequenceNumber is a thread safe increasing sequence number generator. |
15 | // Its constructor doesn't emit a static initializer, so it's safe to use as a | ||||
16 | // global variable or static member. | ||||
[email protected] | 8a8443f | 2012-03-13 12:07:19 | [diff] [blame] | 17 | class AtomicSequenceNumber { |
18 | public: | ||||
tzik | ad6d8a9b | 2017-07-12 09:54:21 | [diff] [blame^] | 19 | constexpr AtomicSequenceNumber() {} |
[email protected] | 8a8443f | 2012-03-13 12:07:19 | [diff] [blame] | 20 | |
tzik | ad6d8a9b | 2017-07-12 09:54:21 | [diff] [blame^] | 21 | // 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] | 8a8443f | 2012-03-13 12:07:19 | [diff] [blame] | 24 | |
25 | private: | ||||
tzik | ad6d8a9b | 2017-07-12 09:54:21 | [diff] [blame^] | 26 | std::atomic_int seq_{0}; |
27 | |||||
[email protected] | 611dbe0 | 2008-08-05 09:57:36 | [diff] [blame] | 28 | DISALLOW_COPY_AND_ASSIGN(AtomicSequenceNumber); |
29 | }; | ||||
30 | |||||
tzik | ad6d8a9b | 2017-07-12 09:54:21 | [diff] [blame^] | 31 | // TODO(tzik): Replace all usage of StaticAtomicSequenceNumber with |
32 | // AtomicSequenceNumber, and remove this alias. | ||||
33 | using StaticAtomicSequenceNumber = AtomicSequenceNumber; | ||||
34 | |||||
[email protected] | 611dbe0 | 2008-08-05 09:57:36 | [diff] [blame] | 35 | } // namespace base |
36 | |||||
37 | #endif // BASE_ATOMIC_SEQUENCE_NUM_H_ |