circular-queue.h 2.1 KB
Newer Older
1
// Copyright 2010 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4 5 6 7

#ifndef V8_CIRCULAR_QUEUE_H_
#define V8_CIRCULAR_QUEUE_H_

8
#include "src/base/atomicops.h"
9
#include "src/globals.h"
10

11 12 13 14 15 16 17
namespace v8 {
namespace internal {


// Lock-free cache-friendly sampling circular queue for large
// records. Intended for fast transfer of large records between a
// single producer and a single consumer. If the queue is full,
18
// StartEnqueue will return NULL. The queue is designed with
19 20
// a goal in mind to evade cache lines thrashing by preventing
// simultaneous reads and writes to adjanced memory locations.
21
template<typename T, unsigned Length>
22 23 24
class SamplingCircularQueue {
 public:
  // Executed on the application thread.
25
  SamplingCircularQueue();
26 27
  ~SamplingCircularQueue();

28 29 30 31 32 33
  // StartEnqueue returns a pointer to a memory location for storing the next
  // record or NULL if all entries are full at the moment.
  T* StartEnqueue();
  // Notifies the queue that the producer has complete writing data into the
  // memory returned by StartEnqueue and it can be passed to the consumer.
  void FinishEnqueue();
34 35

  // Executed on the consumer (analyzer) thread.
36 37 38 39 40
  // Retrieves, but does not remove, the head of this queue, returning NULL
  // if this queue is empty. After the record had been read by a consumer,
  // Remove must be called.
  T* Peek();
  void Remove();
41 42

 private:
43
  // Reserved values for the entry marker.
44
  enum {
45 46 47
    kEmpty,  // Marks clean (processed) entries.
    kFull    // Marks entries already filled by the producer but not yet
             // completely processed by the consumer.
48 49
  };

50
  struct V8_ALIGNED(PROCESSOR_CACHE_LINE_SIZE) Entry {
51 52
    Entry() : marker(kEmpty) {}
    T record;
53
    base::Atomic32 marker;
54 55
  };

56
  Entry* Next(Entry* entry);
57

58
  Entry buffer_[Length];
59 60
  V8_ALIGNED(PROCESSOR_CACHE_LINE_SIZE) Entry* enqueue_pos_;
  V8_ALIGNED(PROCESSOR_CACHE_LINE_SIZE) Entry* dequeue_pos_;
61 62

  DISALLOW_COPY_AND_ASSIGN(SamplingCircularQueue);
63 64 65 66 67 68
};


} }  // namespace v8::internal

#endif  // V8_CIRCULAR_QUEUE_H_