Line data Source code
1 : /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 : /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 : // Copyright (c) 2012 The Chromium Authors. All rights reserved.
4 : // Use of this source code is governed by a BSD-style license that can be
5 : // found in the LICENSE file.
6 :
7 : #ifndef BASE_ATOMIC_SEQUENCE_NUM_H_
8 : #define BASE_ATOMIC_SEQUENCE_NUM_H_
9 :
10 : #include "base/atomicops.h"
11 : #include "base/basictypes.h"
12 :
13 : namespace base {
14 :
15 : class AtomicSequenceNumber;
16 :
17 : // Static (POD) AtomicSequenceNumber that MUST be used in global scope (or
18 : // non-function scope) ONLY. This implementation does not generate any static
19 : // initializer. Note that it does not implement any constructor which means
20 : // that its fields are not initialized except when it is stored in the global
21 : // data section (.data in ELF). If you want to allocate an atomic sequence
22 : // number on the stack (or heap), please use the AtomicSequenceNumber class
23 : // declared below.
24 : class StaticAtomicSequenceNumber {
25 : public:
26 15 : inline int GetNext() {
27 : return static_cast<int>(
28 15 : base::subtle::NoBarrier_AtomicIncrement(&seq_, 1) - 1);
29 : }
30 :
31 : private:
32 : friend class AtomicSequenceNumber;
33 :
34 : inline void Reset() {
35 : base::subtle::Release_Store(&seq_, 0);
36 : }
37 :
38 : base::subtle::Atomic32 seq_;
39 : };
40 :
41 : // AtomicSequenceNumber that can be stored and used safely (i.e. its fields are
42 : // always initialized as opposed to StaticAtomicSequenceNumber declared above).
43 : // Please use StaticAtomicSequenceNumber if you want to declare an atomic
44 : // sequence number in the global scope.
45 : class AtomicSequenceNumber {
46 : public:
47 : AtomicSequenceNumber() {
48 : seq_.Reset();
49 : }
50 :
51 : inline int GetNext() {
52 : return seq_.GetNext();
53 : }
54 :
55 : private:
56 : StaticAtomicSequenceNumber seq_;
57 : DISALLOW_COPY_AND_ASSIGN(AtomicSequenceNumber);
58 : };
59 :
60 : } // namespace base
61 :
62 : #endif // BASE_ATOMIC_SEQUENCE_NUM_H_
|