locked-queue-inl.h 2.29 KB
Newer Older
1 2 3 4
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
#ifndef V8_UTILS_LOCKED_QUEUE_INL_H_
#define V8_UTILS_LOCKED_QUEUE_INL_H_
7

lpy's avatar
lpy committed
8
#include "src/base/atomic-utils.h"
9
#include "src/utils/locked-queue.h"
10 11 12 13 14 15 16 17

namespace v8 {
namespace internal {

template <typename Record>
struct LockedQueue<Record>::Node : Malloced {
  Node() : next(nullptr) {}
  Record value;
lpy's avatar
lpy committed
18
  base::AtomicValue<Node*> next;
19 20 21 22 23
};

template <typename Record>
inline LockedQueue<Record>::LockedQueue() {
  head_ = new Node();
24
  CHECK_NOT_NULL(head_);
25
  tail_ = head_;
26
  size_ = 0;
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
}

template <typename Record>
inline LockedQueue<Record>::~LockedQueue() {
  // Destroy all remaining nodes. Note that we do not destroy the actual values.
  Node* old_node = nullptr;
  Node* cur_node = head_;
  while (cur_node != nullptr) {
    old_node = cur_node;
    cur_node = cur_node->next.Value();
    delete old_node;
  }
}

template <typename Record>
42
inline void LockedQueue<Record>::Enqueue(Record record) {
43
  Node* n = new Node();
44
  CHECK_NOT_NULL(n);
45
  n->value = std::move(record);
46
  {
47
    base::MutexGuard guard(&tail_mutex_);
48
    size_++;
49 50 51 52 53 54 55 56 57
    tail_->next.SetValue(n);
    tail_ = n;
  }
}

template <typename Record>
inline bool LockedQueue<Record>::Dequeue(Record* record) {
  Node* old_head = nullptr;
  {
58
    base::MutexGuard guard(&head_mutex_);
59 60 61
    old_head = head_;
    Node* const next_node = head_->next.Value();
    if (next_node == nullptr) return false;
62
    *record = std::move(next_node->value);
63
    head_ = next_node;
64 65 66
    size_t old_size = size_.fetch_sub(1);
    USE(old_size);
    DCHECK_GT(old_size, 0);
67 68 69 70 71 72 73
  }
  delete old_head;
  return true;
}

template <typename Record>
inline bool LockedQueue<Record>::IsEmpty() const {
74
  base::MutexGuard guard(&head_mutex_);
75 76 77 78 79
  return head_->next.Value() == nullptr;
}

template <typename Record>
inline bool LockedQueue<Record>::Peek(Record* record) const {
80
  base::MutexGuard guard(&head_mutex_);
81 82 83 84 85 86
  Node* const next_node = head_->next.Value();
  if (next_node == nullptr) return false;
  *record = next_node->value;
  return true;
}

87 88 89 90 91
template <typename Record>
inline size_t LockedQueue<Record>::size() const {
  return size_;
}

92 93 94
}  // namespace internal
}  // namespace v8

95
#endif  // V8_UTILS_LOCKED_QUEUE_INL_H_