GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_platform.cc Lines: 352 367 95.9 %
Date: 2020-08-22 22:13:06 Branches: 93 120 77.5 %

Line Branch Exec Source
1
#include "node_platform.h"
2
#include "node_internals.h"
3
4
#include "env-inl.h"
5
#include "debug_utils-inl.h"
6
#include <algorithm>  // find_if(), find(), move()
7
#include <cmath>  // llround()
8
#include <memory>  // unique_ptr(), shared_ptr(), make_shared()
9
10
namespace node {
11
12
using v8::Isolate;
13
using v8::Object;
14
using v8::Platform;
15
using v8::Task;
16
17
namespace {
18
19
struct PlatformWorkerData {
20
  TaskQueue<Task>* task_queue;
21
  Mutex* platform_workers_mutex;
22
  ConditionVariable* platform_workers_ready;
23
  int* pending_platform_workers;
24
  int id;
25
};
26
27
17605
static void PlatformWorkerThread(void* data) {
28
  std::unique_ptr<PlatformWorkerData>
29
35223
      worker_data(static_cast<PlatformWorkerData*>(data));
30
31
17574
  TaskQueue<Task>* pending_worker_tasks = worker_data->task_queue;
32

34988
  TRACE_EVENT_METADATA1("__metadata", "thread_name", "name",
33
                        "PlatformWorkerThread");
34
35
  // Notify the main thread that the platform worker is ready.
36
  {
37
35223
    Mutex::ScopedLock lock(*worker_data->platform_workers_mutex);
38
17646
    (*worker_data->pending_platform_workers)--;
39
17646
    worker_data->platform_workers_ready->Signal(lock);
40
  }
41
42
162720
  while (std::unique_ptr<Task> task = pending_worker_tasks->BlockingPop()) {
43
72291
    task->Run();
44
72348
    pending_worker_tasks->NotifyOfCompletion();
45
72541
  }
46
17618
}
47
48
}  // namespace
49
50
4403
class WorkerThreadsTaskRunner::DelayedTaskScheduler {
51
 public:
52
4410
  explicit DelayedTaskScheduler(TaskQueue<Task>* tasks)
53
4410
    : pending_worker_tasks_(tasks) {}
54
55
4410
  std::unique_ptr<uv_thread_t> Start() {
56
13230
    auto start_thread = [](void* data) {
57
4410
      static_cast<DelayedTaskScheduler*>(data)->Run();
58
13223
    };
59
4410
    std::unique_ptr<uv_thread_t> t { new uv_thread_t() };
60
4410
    uv_sem_init(&ready_, 0);
61
4410
    CHECK_EQ(0, uv_thread_create(t.get(), start_thread, this));
62
4410
    uv_sem_wait(&ready_);
63
4410
    uv_sem_destroy(&ready_);
64
4410
    return t;
65
  }
66
67
73
  void PostDelayedTask(std::unique_ptr<Task> task, double delay_in_seconds) {
68
146
    tasks_.Push(std::make_unique<ScheduleTask>(this, std::move(task),
69
73
                                               delay_in_seconds));
70
73
    uv_async_send(&flush_tasks_);
71
73
  }
72
73
4403
  void Stop() {
74
4403
    tasks_.Push(std::make_unique<StopTask>(this));
75
4403
    uv_async_send(&flush_tasks_);
76
4403
  }
77
78
 private:
79
4410
  void Run() {
80

8820
    TRACE_EVENT_METADATA1("__metadata", "thread_name", "name",
81
                          "WorkerThreadsTaskRunner::DelayedTaskScheduler");
82
4410
    loop_.data = this;
83
4410
    CHECK_EQ(0, uv_loop_init(&loop_));
84
4410
    flush_tasks_.data = this;
85
4410
    CHECK_EQ(0, uv_async_init(&loop_, &flush_tasks_, FlushTasks));
86
4410
    uv_sem_post(&ready_);
87
88
4410
    uv_run(&loop_, UV_RUN_DEFAULT);
89
4403
    CheckedUvLoopClose(&loop_);
90
4403
  }
91
92
4472
  static void FlushTasks(uv_async_t* flush_tasks) {
93
    DelayedTaskScheduler* scheduler =
94
4472
        ContainerOf(&DelayedTaskScheduler::loop_, flush_tasks->loop);
95
13424
    while (std::unique_ptr<Task> task = scheduler->tasks_.Pop())
96
8952
      task->Run();
97
4472
  }
98
99
8806
  class StopTask : public Task {
100
   public:
101
4403
    explicit StopTask(DelayedTaskScheduler* scheduler): scheduler_(scheduler) {}
102
103
4403
    void Run() override {
104
8806
      std::vector<uv_timer_t*> timers;
105
4475
      for (uv_timer_t* timer : scheduler_->timers_)
106
72
        timers.push_back(timer);
107
4475
      for (uv_timer_t* timer : timers)
108
72
        scheduler_->TakeTimerTask(timer);
109
8806
      uv_close(reinterpret_cast<uv_handle_t*>(&scheduler_->flush_tasks_),
110
17612
               [](uv_handle_t* handle) {});
111
4403
    }
112
113
   private:
114
     DelayedTaskScheduler* scheduler_;
115
  };
116
117
146
  class ScheduleTask : public Task {
118
   public:
119
73
    ScheduleTask(DelayedTaskScheduler* scheduler,
120
                 std::unique_ptr<Task> task,
121
                 double delay_in_seconds)
122
73
      : scheduler_(scheduler),
123
73
        task_(std::move(task)),
124
146
        delay_in_seconds_(delay_in_seconds) {}
125
126
73
    void Run() override {
127
73
      uint64_t delay_millis = llround(delay_in_seconds_ * 1000);
128
146
      std::unique_ptr<uv_timer_t> timer(new uv_timer_t());
129
73
      CHECK_EQ(0, uv_timer_init(&scheduler_->loop_, timer.get()));
130
73
      timer->data = task_.release();
131
73
      CHECK_EQ(0, uv_timer_start(timer.get(), RunTask, delay_millis, 0));
132
73
      scheduler_->timers_.insert(timer.release());
133
73
    }
134
135
   private:
136
    DelayedTaskScheduler* scheduler_;
137
    std::unique_ptr<Task> task_;
138
    double delay_in_seconds_;
139
  };
140
141
1
  static void RunTask(uv_timer_t* timer) {
142
    DelayedTaskScheduler* scheduler =
143
1
        ContainerOf(&DelayedTaskScheduler::loop_, timer->loop);
144
1
    scheduler->pending_worker_tasks_->Push(scheduler->TakeTimerTask(timer));
145
1
  }
146
147
73
  std::unique_ptr<Task> TakeTimerTask(uv_timer_t* timer) {
148
73
    std::unique_ptr<Task> task(static_cast<Task*>(timer->data));
149
73
    uv_timer_stop(timer);
150
365
    uv_close(reinterpret_cast<uv_handle_t*>(timer), [](uv_handle_t* handle) {
151
73
      delete reinterpret_cast<uv_timer_t*>(handle);
152
292
    });
153
73
    timers_.erase(timer);
154
73
    return task;
155
  }
156
157
  uv_sem_t ready_;
158
  TaskQueue<Task>* pending_worker_tasks_;
159
160
  TaskQueue<Task> tasks_;
161
  uv_loop_t loop_;
162
  uv_async_t flush_tasks_;
163
  std::unordered_set<uv_timer_t*> timers_;
164
};
165
166
4410
WorkerThreadsTaskRunner::WorkerThreadsTaskRunner(int thread_pool_size) {
167
8820
  Mutex platform_workers_mutex;
168
8820
  ConditionVariable platform_workers_ready;
169
170
8820
  Mutex::ScopedLock lock(platform_workers_mutex);
171
4410
  int pending_platform_workers = thread_pool_size;
172
173
8820
  delayed_task_scheduler_ = std::make_unique<DelayedTaskScheduler>(
174
13230
      &pending_worker_tasks_);
175
4410
  threads_.push_back(delayed_task_scheduler_->Start());
176
177
22056
  for (int i = 0; i < thread_pool_size; i++) {
178
    PlatformWorkerData* worker_data = new PlatformWorkerData{
179
17646
      &pending_worker_tasks_, &platform_workers_mutex,
180
      &platform_workers_ready, &pending_platform_workers, i
181
35292
    };
182
35292
    std::unique_ptr<uv_thread_t> t { new uv_thread_t() };
183
17646
    if (uv_thread_create(t.get(), PlatformWorkerThread,
184
                         worker_data) != 0) {
185
      break;
186
    }
187
17646
    threads_.push_back(std::move(t));
188
  }
189
190
  // Wait for platform workers to initialize before continuing with the
191
  // bootstrap.
192
35044
  while (pending_platform_workers > 0) {
193
15317
    platform_workers_ready.Wait(lock);
194
  }
195
4410
}
196
197
72550
void WorkerThreadsTaskRunner::PostTask(std::unique_ptr<Task> task) {
198
72550
  pending_worker_tasks_.Push(std::move(task));
199
72550
}
200
201
73
void WorkerThreadsTaskRunner::PostDelayedTask(std::unique_ptr<Task> task,
202
                                              double delay_in_seconds) {
203
73
  delayed_task_scheduler_->PostDelayedTask(std::move(task), delay_in_seconds);
204
73
}
205
206
10935
void WorkerThreadsTaskRunner::BlockingDrain() {
207
10935
  pending_worker_tasks_.BlockingDrain();
208
10935
}
209
210
4403
void WorkerThreadsTaskRunner::Shutdown() {
211
4403
  pending_worker_tasks_.Stop();
212
4403
  delayed_task_scheduler_->Stop();
213
26424
  for (size_t i = 0; i < threads_.size(); i++) {
214
22021
    CHECK_EQ(0, uv_thread_join(threads_[i].get()));
215
  }
216
4403
}
217
218
4487
int WorkerThreadsTaskRunner::NumberOfWorkerThreads() const {
219
4487
  return threads_.size();
220
}
221
222
4876
PerIsolatePlatformData::PerIsolatePlatformData(
223
4876
    Isolate* isolate, uv_loop_t* loop)
224
4876
  : isolate_(isolate), loop_(loop) {
225
4876
  flush_tasks_ = new uv_async_t();
226
4876
  CHECK_EQ(0, uv_async_init(loop, flush_tasks_, FlushTasks));
227
4876
  flush_tasks_->data = static_cast<void*>(this);
228
4876
  uv_unref(reinterpret_cast<uv_handle_t*>(flush_tasks_));
229
4876
}
230
231
std::shared_ptr<v8::TaskRunner>
232
26470
PerIsolatePlatformData::GetForegroundTaskRunner() {
233
26470
  return shared_from_this();
234
}
235
236
6520
void PerIsolatePlatformData::FlushTasks(uv_async_t* handle) {
237
6520
  auto platform_data = static_cast<PerIsolatePlatformData*>(handle->data);
238
6520
  platform_data->FlushForegroundTasksInternal();
239
6520
}
240
241
void PerIsolatePlatformData::PostIdleTask(std::unique_ptr<v8::IdleTask> task) {
242
  UNREACHABLE();
243
}
244
245
7041
void PerIsolatePlatformData::PostTask(std::unique_ptr<Task> task) {
246
7041
  if (flush_tasks_ == nullptr) {
247
    // V8 may post tasks during Isolate disposal. In that case, the only
248
    // sensible path forward is to discard the task.
249
    return;
250
  }
251
7041
  foreground_tasks_.Push(std::move(task));
252
7041
  uv_async_send(flush_tasks_);
253
}
254
255
4321
void PerIsolatePlatformData::PostDelayedTask(
256
    std::unique_ptr<Task> task, double delay_in_seconds) {
257
4321
  if (flush_tasks_ == nullptr) {
258
    // V8 may post tasks during Isolate disposal. In that case, the only
259
    // sensible path forward is to discard the task.
260
    return;
261
  }
262
8642
  std::unique_ptr<DelayedTask> delayed(new DelayedTask());
263
4321
  delayed->task = std::move(task);
264
4321
  delayed->platform_data = shared_from_this();
265
4321
  delayed->timeout = delay_in_seconds;
266
4321
  foreground_delayed_tasks_.Push(std::move(delayed));
267
4321
  uv_async_send(flush_tasks_);
268
}
269
270
1625
void PerIsolatePlatformData::PostNonNestableTask(std::unique_ptr<Task> task) {
271
1625
  PostTask(std::move(task));
272
1625
}
273
274
void PerIsolatePlatformData::PostNonNestableDelayedTask(
275
    std::unique_ptr<Task> task,
276
    double delay_in_seconds) {
277
  PostDelayedTask(std::move(task), delay_in_seconds);
278
}
279
280
954
PerIsolatePlatformData::~PerIsolatePlatformData() {
281
477
  CHECK(!flush_tasks_);
282
478
}
283
284
427
void PerIsolatePlatformData::AddShutdownCallback(void (*callback)(void*),
285
                                                 void* data) {
286
427
  shutdown_callbacks_.emplace_back(ShutdownCallback { callback, data });
287
427
}
288
289
4413
void PerIsolatePlatformData::Shutdown() {
290
4413
  if (flush_tasks_ == nullptr)
291
    return;
292
293
  // While there should be no V8 tasks in the queues at this point, it is
294
  // possible that Node.js-internal tasks from e.g. the inspector are still
295
  // lying around. We clear these queues and ignore the return value,
296
  // effectively deleting the tasks instead of running them.
297
4413
  foreground_delayed_tasks_.PopAll();
298
4413
  foreground_tasks_.PopAll();
299
4413
  scheduled_delayed_tasks_.clear();
300
301
  // Both destroying the scheduled_delayed_tasks_ lists and closing
302
  // flush_tasks_ handle add tasks to the event loop. We keep a count of all
303
  // non-closed handles, and when that reaches zero, we inform any shutdown
304
  // callbacks that the platform is done as far as this Isolate is concerned.
305
4413
  self_reference_ = shared_from_this();
306
8826
  uv_close(reinterpret_cast<uv_handle_t*>(flush_tasks_),
307
5369
           [](uv_handle_t* handle) {
308
    std::unique_ptr<uv_async_t> flush_tasks {
309
956
        reinterpret_cast<uv_async_t*>(handle) };
310
    PerIsolatePlatformData* platform_data =
311
478
        static_cast<PerIsolatePlatformData*>(flush_tasks->data);
312
477
    platform_data->DecreaseHandleCount();
313
478
    platform_data->self_reference_.reset();
314
9782
  });
315
4413
  flush_tasks_ = nullptr;
316
}
317
318
921
void PerIsolatePlatformData::DecreaseHandleCount() {
319
921
  CHECK_GE(uv_handle_count_, 1);
320
921
  if (--uv_handle_count_ == 0) {
321
905
    for (const auto& callback : shutdown_callbacks_)
322
427
      callback.cb(callback.data);
323
  }
324
921
}
325
326
4410
NodePlatform::NodePlatform(int thread_pool_size,
327
4410
                           v8::TracingController* tracing_controller) {
328
4410
  if (tracing_controller != nullptr) {
329
4403
    tracing_controller_ = tracing_controller;
330
  } else {
331
7
    tracing_controller_ = new v8::TracingController();
332
  }
333
  // TODO(addaleax): It's a bit icky that we use global state here, but we can't
334
  // really do anything about it unless V8 starts exposing a way to access the
335
  // current v8::Platform instance.
336
4410
  SetTracingController(tracing_controller_);
337
  DCHECK_EQ(GetTracingController(), tracing_controller_);
338
  worker_thread_task_runner_ =
339
4410
      std::make_shared<WorkerThreadsTaskRunner>(thread_pool_size);
340
4410
}
341
342
13209
NodePlatform::~NodePlatform() {
343
4403
  Shutdown();
344
8806
}
345
346
4875
void NodePlatform::RegisterIsolate(Isolate* isolate, uv_loop_t* loop) {
347
9750
  Mutex::ScopedLock lock(per_isolate_mutex_);
348
9750
  auto delegate = std::make_shared<PerIsolatePlatformData>(isolate, loop);
349
4875
  IsolatePlatformDelegate* ptr = delegate.get();
350
  auto insertion = per_isolate_.emplace(
351
    isolate,
352
4875
    std::make_pair(ptr, std::move(delegate)));
353
4875
  CHECK(insertion.second);
354
4875
}
355
356
1
void NodePlatform::RegisterIsolate(Isolate* isolate,
357
                                   IsolatePlatformDelegate* delegate) {
358
2
  Mutex::ScopedLock lock(per_isolate_mutex_);
359
  auto insertion = per_isolate_.emplace(
360
    isolate,
361
1
    std::make_pair(delegate, std::shared_ptr<PerIsolatePlatformData>{}));
362
1
  CHECK(insertion.second);
363
1
}
364
365
4413
void NodePlatform::UnregisterIsolate(Isolate* isolate) {
366
8826
  Mutex::ScopedLock lock(per_isolate_mutex_);
367
4413
  auto existing_it = per_isolate_.find(isolate);
368
4413
  CHECK_NE(existing_it, per_isolate_.end());
369
4413
  auto& existing = existing_it->second;
370
4413
  if (existing.second) {
371
4412
    existing.second->Shutdown();
372
  }
373
4413
  per_isolate_.erase(existing_it);
374
4413
}
375
376
424
void NodePlatform::AddIsolateFinishedCallback(Isolate* isolate,
377
                                              void (*cb)(void*), void* data) {
378
851
  Mutex::ScopedLock lock(per_isolate_mutex_);
379
427
  auto it = per_isolate_.find(isolate);
380
427
  if (it == per_isolate_.end()) {
381
    cb(data);
382
    return;
383
  }
384
427
  CHECK(it->second.second);
385
427
  it->second.second->AddShutdownCallback(cb, data);
386
}
387
388
8801
void NodePlatform::Shutdown() {
389
8801
  if (has_shut_down_) return;
390
4403
  has_shut_down_ = true;
391
4403
  worker_thread_task_runner_->Shutdown();
392
393
  {
394
8806
    Mutex::ScopedLock lock(per_isolate_mutex_);
395
4403
    per_isolate_.clear();
396
  }
397
}
398
399
4487
int NodePlatform::NumberOfWorkerThreads() {
400
4487
  return worker_thread_task_runner_->NumberOfWorkerThreads();
401
}
402
403
6829
void PerIsolatePlatformData::RunForegroundTask(std::unique_ptr<Task> task) {
404
6829
  DebugSealHandleScope scope(isolate_);
405
6829
  Environment* env = Environment::GetCurrent(isolate_);
406
6829
  if (env != nullptr) {
407
12347
    v8::HandleScope scope(isolate_);
408
6174
    InternalCallbackScope cb_scope(env, Object::New(isolate_), { 0, 0 },
409
18522
                                   InternalCallbackScope::kNoFlags);
410
6174
    task->Run();
411
  } else {
412
655
    task->Run();
413
  }
414
6828
}
415
416
21
void PerIsolatePlatformData::DeleteFromScheduledTasks(DelayedTask* task) {
417
  auto it = std::find_if(scheduled_delayed_tasks_.begin(),
418
                         scheduled_delayed_tasks_.end(),
419
42
                         [task](const DelayedTaskPointer& delayed) -> bool {
420
42
          return delayed.get() == task;
421
21
      });
422
21
  CHECK_NE(it, scheduled_delayed_tasks_.end());
423
21
  scheduled_delayed_tasks_.erase(it);
424
21
}
425
426
21
void PerIsolatePlatformData::RunForegroundTask(uv_timer_t* handle) {
427
21
  DelayedTask* delayed = ContainerOf(&DelayedTask::timer, handle);
428
21
  delayed->platform_data->RunForegroundTask(std::move(delayed->task));
429
21
  delayed->platform_data->DeleteFromScheduledTasks(delayed);
430
21
}
431
432
8722
void NodePlatform::DrainTasks(Isolate* isolate) {
433
17443
  std::shared_ptr<PerIsolatePlatformData> per_isolate = ForNodeIsolate(isolate);
434
8723
  if (!per_isolate) return;
435
436

10935
  do {
437
    // Worker tasks aren't associated with an Isolate.
438
10935
    worker_thread_task_runner_->BlockingDrain();
439
10935
  } while (per_isolate->FlushForegroundTasksInternal());
440
}
441
442
17459
bool PerIsolatePlatformData::FlushForegroundTasksInternal() {
443
17459
  bool did_work = false;
444
445
  while (std::unique_ptr<DelayedTask> delayed =
446
25699
      foreground_delayed_tasks_.Pop()) {
447
4120
    did_work = true;
448
4120
    uint64_t delay_millis = llround(delayed->timeout * 1000);
449
450
4120
    delayed->timer.data = static_cast<void*>(delayed.get());
451
4120
    uv_timer_init(loop_, &delayed->timer);
452
    // Timers may not guarantee queue ordering of events with the same delay if
453
    // the delay is non-zero. This should not be a problem in practice.
454
4120
    uv_timer_start(&delayed->timer, RunForegroundTask, delay_millis, 0);
455
4120
    uv_unref(reinterpret_cast<uv_handle_t*>(&delayed->timer));
456
4120
    uv_handle_count_++;
457
458
8240
    scheduled_delayed_tasks_.emplace_back(delayed.release(),
459
12132
                                          [](DelayedTask* delayed) {
460
8012
      uv_close(reinterpret_cast<uv_handle_t*>(&delayed->timer),
461
4891
               [](uv_handle_t* handle) {
462
        std::unique_ptr<DelayedTask> task {
463
886
            static_cast<DelayedTask*>(handle->data) };
464
443
        task->platform_data->DecreaseHandleCount();
465
8897
      });
466
16252
    });
467
4120
  }
468
  // Move all foreground tasks into a separate queue and flush that queue.
469
  // This way tasks that are posted while flushing the queue will be run on the
470
  // next call of FlushForegroundTasksInternal.
471
34917
  std::queue<std::unique_ptr<Task>> tasks = foreground_tasks_.PopAll();
472
31073
  while (!tasks.empty()) {
473
13615
    std::unique_ptr<Task> task = std::move(tasks.front());
474
6808
    tasks.pop();
475
6808
    did_work = true;
476
6808
    RunForegroundTask(std::move(task));
477
  }
478
34914
  return did_work;
479
}
480
481
72550
void NodePlatform::CallOnWorkerThread(std::unique_ptr<Task> task) {
482
72550
  worker_thread_task_runner_->PostTask(std::move(task));
483
72550
}
484
485
73
void NodePlatform::CallDelayedOnWorkerThread(std::unique_ptr<Task> task,
486
                                             double delay_in_seconds) {
487
146
  worker_thread_task_runner_->PostDelayedTask(std::move(task),
488
73
                                              delay_in_seconds);
489
73
}
490
491
492
26470
IsolatePlatformDelegate* NodePlatform::ForIsolate(Isolate* isolate) {
493
52940
  Mutex::ScopedLock lock(per_isolate_mutex_);
494
52940
  auto data = per_isolate_[isolate];
495
26470
  CHECK_NOT_NULL(data.first);
496
52940
  return data.first;
497
}
498
499
std::shared_ptr<PerIsolatePlatformData>
500
8726
NodePlatform::ForNodeIsolate(Isolate* isolate) {
501
17453
  Mutex::ScopedLock lock(per_isolate_mutex_);
502
17454
  auto data = per_isolate_[isolate];
503
8727
  CHECK_NOT_NULL(data.first);
504
17454
  return data.second;
505
}
506
507
4
bool NodePlatform::FlushForegroundTasks(Isolate* isolate) {
508
8
  std::shared_ptr<PerIsolatePlatformData> per_isolate = ForNodeIsolate(isolate);
509
4
  if (!per_isolate) return false;
510
4
  return per_isolate->FlushForegroundTasksInternal();
511
}
512
513
bool NodePlatform::IdleTasksEnabled(Isolate* isolate) {
514
  return ForIsolate(isolate)->IdleTasksEnabled();
515
}
516
517
std::shared_ptr<v8::TaskRunner>
518
26470
NodePlatform::GetForegroundTaskRunner(Isolate* isolate) {
519
26470
  return ForIsolate(isolate)->GetForegroundTaskRunner();
520
}
521
522
975650
double NodePlatform::MonotonicallyIncreasingTime() {
523
  // Convert nanos to seconds.
524
975650
  return uv_hrtime() / 1e9;
525
}
526
527
21684415
double NodePlatform::CurrentClockTimeMillis() {
528
21684415
  return SystemClockTimeMillis();
529
}
530
531
278954
v8::TracingController* NodePlatform::GetTracingController() {
532
278954
  CHECK_NOT_NULL(tracing_controller_);
533
278954
  return tracing_controller_;
534
}
535
536
4410
Platform::StackTracePrinter NodePlatform::GetStackTracePrinter() {
537
4410
  return []() {
538
    fprintf(stderr, "\n");
539
    DumpBacktrace(stderr);
540
    fflush(stderr);
541
8820
  };
542
}
543
544
template <class T>
545
18572
TaskQueue<T>::TaskQueue()
546
    : lock_(), tasks_available_(), tasks_drained_(),
547
18572
      outstanding_tasks_(0), stopped_(false), task_queue_() { }
548
549
template <class T>
550
88389
void TaskQueue<T>::Push(std::unique_ptr<T> task) {
551
176778
  Mutex::ScopedLock scoped_lock(lock_);
552
88389
  outstanding_tasks_++;
553
88389
  task_queue_.push(std::move(task));
554
88389
  tasks_available_.Signal(scoped_lock);
555
88389
}
556
557
template <class T>
558
30527
std::unique_ptr<T> TaskQueue<T>::Pop() {
559
61054
  Mutex::ScopedLock scoped_lock(lock_);
560

30527
  if (task_queue_.empty()) {
561
21931
    return std::unique_ptr<T>(nullptr);
562
  }
563
17192
  std::unique_ptr<T> result = std::move(task_queue_.front());
564
8596
  task_queue_.pop();
565
8596
  return result;
566
}
567
568
template <class T>
569
90165
std::unique_ptr<T> TaskQueue<T>::BlockingPop() {
570
180331
  Mutex::ScopedLock scoped_lock(lock_);
571

256716
  while (task_queue_.empty() && !stopped_) {
572
83289
    tasks_available_.Wait(scoped_lock);
573
  }
574
90166
  if (stopped_) {
575
17618
    return std::unique_ptr<T>(nullptr);
576
  }
577
145096
  std::unique_ptr<T> result = std::move(task_queue_.front());
578
72548
  task_queue_.pop();
579
72548
  return result;
580
}
581
582
template <class T>
583
72352
void TaskQueue<T>::NotifyOfCompletion() {
584
144900
  Mutex::ScopedLock scoped_lock(lock_);
585
72548
  if (--outstanding_tasks_ == 0) {
586
38220
    tasks_drained_.Broadcast(scoped_lock);
587
  }
588
72520
}
589
590
template <class T>
591
10935
void TaskQueue<T>::BlockingDrain() {
592
21870
  Mutex::ScopedLock scoped_lock(lock_);
593
12277
  while (outstanding_tasks_ > 0) {
594
671
    tasks_drained_.Wait(scoped_lock);
595
  }
596
10935
}
597
598
template <class T>
599
4403
void TaskQueue<T>::Stop() {
600
8806
  Mutex::ScopedLock scoped_lock(lock_);
601
4403
  stopped_ = true;
602
4403
  tasks_available_.Broadcast(scoped_lock);
603
4403
}
604
605
template <class T>
606
26285
std::queue<std::unique_ptr<T>> TaskQueue<T>::PopAll() {
607
52569
  Mutex::ScopedLock scoped_lock(lock_);
608
26285
  std::queue<std::unique_ptr<T>> result;
609
26285
  result.swap(task_queue_);
610
52569
  return result;
611
}
612
613

13395
}  // namespace node