• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2018 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 
5 #ifndef BASE_TASK_SEQUENCE_MANAGER_ENQUEUE_ORDER_H_
6 #define BASE_TASK_SEQUENCE_MANAGER_ENQUEUE_ORDER_H_
7 
8 #include <stdint.h>
9 
10 #include <atomic>
11 
12 #include "base/base_export.h"
13 #include "base/macros.h"
14 
15 namespace base {
16 namespace sequence_manager {
17 namespace internal {
18 
19 // 64-bit number which is used to order tasks.
20 // SequenceManager assumes this number will never overflow.
21 class EnqueueOrder {
22  public:
EnqueueOrder()23   EnqueueOrder() : value_(kNone) {}
24   ~EnqueueOrder() = default;
25 
none()26   static EnqueueOrder none() { return EnqueueOrder(kNone); }
blocking_fence()27   static EnqueueOrder blocking_fence() { return EnqueueOrder(kBlockingFence); }
28 
29   // It's okay to use EnqueueOrder in boolean expressions keeping in mind
30   // that some non-zero values have a special meaning.
uint64_t()31   operator uint64_t() const { return value_; }
32 
FromIntForTesting(uint64_t value)33   static EnqueueOrder FromIntForTesting(uint64_t value) {
34     return EnqueueOrder(value);
35   }
36 
37   // EnqueueOrder can't be created from a raw number in non-test code.
38   // Generator is used to create it with strictly monotonic guarantee.
39   class BASE_EXPORT Generator {
40    public:
41     Generator();
42     ~Generator();
43 
44     // Can be called from any thread.
GenerateNext()45     EnqueueOrder GenerateNext() {
46       return EnqueueOrder(std::atomic_fetch_add_explicit(
47           &counter_, uint64_t(1), std::memory_order_relaxed));
48     }
49 
50    private:
51     std::atomic<uint64_t> counter_;
52     DISALLOW_COPY_AND_ASSIGN(Generator);
53   };
54 
55  private:
EnqueueOrder(uint64_t value)56   explicit EnqueueOrder(uint64_t value) : value_(value) {}
57 
58   enum SpecialValues : uint64_t {
59     kNone = 0,
60     kBlockingFence = 1,
61     kFirst = 2,
62   };
63 
64   uint64_t value_;
65 };
66 
67 }  // namespace internal
68 }  // namespace sequence_manager
69 }  // namespace base
70 
71 #endif  // BASE_TASK_SEQUENCE_MANAGER_ENQUEUE_ORDER_H_
72