• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2010 the V8 project 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 V8_PROFILER_CIRCULAR_QUEUE_H_
6 #define V8_PROFILER_CIRCULAR_QUEUE_H_
7 
8 #include "src/base/atomicops.h"
9 #include "src/common/globals.h"
10 
11 namespace v8 {
12 namespace internal {
13 
14 // Lock-free cache-friendly sampling circular queue for large
15 // records. Intended for fast transfer of large records between a
16 // single producer and a single consumer. If the queue is full,
17 // StartEnqueue will return nullptr. The queue is designed with
18 // a goal in mind to evade cache lines thrashing by preventing
19 // simultaneous reads and writes to adjanced memory locations.
20 template<typename T, unsigned Length>
21 class SamplingCircularQueue {
22  public:
23   // Executed on the application thread.
24   SamplingCircularQueue();
25   ~SamplingCircularQueue();
26   SamplingCircularQueue(const SamplingCircularQueue&) = delete;
27   SamplingCircularQueue& operator=(const SamplingCircularQueue&) = delete;
28 
29   // StartEnqueue returns a pointer to a memory location for storing the next
30   // record or nullptr if all entries are full at the moment.
31   T* StartEnqueue();
32   // Notifies the queue that the producer has complete writing data into the
33   // memory returned by StartEnqueue and it can be passed to the consumer.
34   void FinishEnqueue();
35 
36   // Executed on the consumer (analyzer) thread.
37   // Retrieves, but does not remove, the head of this queue, returning nullptr
38   // if this queue is empty. After the record had been read by a consumer,
39   // Remove must be called.
40   T* Peek();
41   void Remove();
42 
43  private:
44   // Reserved values for the entry marker.
45   enum {
46     kEmpty,  // Marks clean (processed) entries.
47     kFull    // Marks entries already filled by the producer but not yet
48              // completely processed by the consumer.
49   };
50 
51   struct alignas(PROCESSOR_CACHE_LINE_SIZE) Entry {
EntryEntry52     Entry() : marker(kEmpty) {}
53     T record;
54     base::Atomic32 marker;
55   };
56 
57   Entry* Next(Entry* entry);
58 
59   Entry buffer_[Length];
60   alignas(PROCESSOR_CACHE_LINE_SIZE) Entry* enqueue_pos_;
61   alignas(PROCESSOR_CACHE_LINE_SIZE) Entry* dequeue_pos_;
62 };
63 
64 
65 }  // namespace internal
66 }  // namespace v8
67 
68 #endif  // V8_PROFILER_CIRCULAR_QUEUE_H_
69