summaryrefslogtreecommitdiff
path: root/deps/v8/src/locked-queue-inl.h
blob: 8b3e9d02bb7ba00267032211b72dc1a8ad85545b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// 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.

#ifndef V8_LOCKED_QUEUE_INL_
#define V8_LOCKED_QUEUE_INL_

#include "src/atomic-utils.h"
#include "src/locked-queue.h"

namespace v8 {
namespace internal {

template <typename Record>
struct LockedQueue<Record>::Node : Malloced {
  Node() : next(nullptr) {}
  Record value;
  AtomicValue<Node*> next;
};


template <typename Record>
inline LockedQueue<Record>::LockedQueue() {
  head_ = new Node();
  CHECK(head_ != nullptr);
  tail_ = head_;
}


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>
inline void LockedQueue<Record>::Enqueue(const Record& record) {
  Node* n = new Node();
  CHECK(n != nullptr);
  n->value = record;
  {
    base::LockGuard<base::Mutex> guard(&tail_mutex_);
    tail_->next.SetValue(n);
    tail_ = n;
  }
}


template <typename Record>
inline bool LockedQueue<Record>::Dequeue(Record* record) {
  Node* old_head = nullptr;
  {
    base::LockGuard<base::Mutex> guard(&head_mutex_);
    old_head = head_;
    Node* const next_node = head_->next.Value();
    if (next_node == nullptr) return false;
    *record = next_node->value;
    head_ = next_node;
  }
  delete old_head;
  return true;
}


template <typename Record>
inline bool LockedQueue<Record>::IsEmpty() const {
  base::LockGuard<base::Mutex> guard(&head_mutex_);
  return head_->next.Value() == nullptr;
}


template <typename Record>
inline bool LockedQueue<Record>::Peek(Record* record) const {
  base::LockGuard<base::Mutex> guard(&head_mutex_);
  Node* const next_node = head_->next.Value();
  if (next_node == nullptr) return false;
  *record = next_node->value;
  return true;
}

}  // namespace internal
}  // namespace v8

#endif  // V8_LOCKED_QUEUE_INL_