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-07-19 22:14:24 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
19616
static void PlatformWorkerThread(void* data) {
28
  std::unique_ptr<PlatformWorkerData>
29
39334
      worker_data(static_cast<PlatformWorkerData*>(data));
30
31
19698
  TaskQueue<Task>* pending_worker_tasks = worker_data->task_queue;
32

39305
  TRACE_EVENT_METADATA1("__metadata", "thread_name", "name",
33
                        "PlatformWorkerThread");
34
35
  // Notify the main thread that the platform worker is ready.
36
  {
37
39448
    Mutex::ScopedLock lock(*worker_data->platform_workers_mutex);
38
19746
    (*worker_data->pending_platform_workers)--;
39
19746
    worker_data->platform_workers_ready->Signal(lock);
40
  }
41
42
169739
  while (std::unique_ptr<Task> task = pending_worker_tasks->BlockingPop()) {
43
74898
    task->Run();
44
74865
    pending_worker_tasks->NotifyOfCompletion();
45
75001
  }
46
19715
}
47
48
}  // namespace
49
50
4928
class WorkerThreadsTaskRunner::DelayedTaskScheduler {
51
 public:
52
4935
  explicit DelayedTaskScheduler(TaskQueue<Task>* tasks)
53
4935
    : pending_worker_tasks_(tasks) {}
54
55
4935
  std::unique_ptr<uv_thread_t> Start() {
56
14805
    auto start_thread = [](void* data) {
57
4935
      static_cast<DelayedTaskScheduler*>(data)->Run();
58
14798
    };
59
4935
    std::unique_ptr<uv_thread_t> t { new uv_thread_t() };
60
4935
    uv_sem_init(&ready_, 0);
61
4935
    CHECK_EQ(0, uv_thread_create(t.get(), start_thread, this));
62
4935
    uv_sem_wait(&ready_);
63
4935
    uv_sem_destroy(&ready_);
64
4935
    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
4928
  void Stop() {
74
4928
    tasks_.Push(std::make_unique<StopTask>(this));
75
4928
    uv_async_send(&flush_tasks_);
76
4928
  }
77
78
 private:
79
4935
  void Run() {
80

9870
    TRACE_EVENT_METADATA1("__metadata", "thread_name", "name",
81
                          "WorkerThreadsTaskRunner::DelayedTaskScheduler");
82
4935
    loop_.data = this;
83
4935
    CHECK_EQ(0, uv_loop_init(&loop_));
84
4935
    flush_tasks_.data = this;
85
4935
    CHECK_EQ(0, uv_async_init(&loop_, &flush_tasks_, FlushTasks));
86
4935
    uv_sem_post(&ready_);
87
88
4935
    uv_run(&loop_, UV_RUN_DEFAULT);
89
4928
    CheckedUvLoopClose(&loop_);
90
4928
  }
91
92
5001
  static void FlushTasks(uv_async_t* flush_tasks) {
93
    DelayedTaskScheduler* scheduler =
94
5001
        ContainerOf(&DelayedTaskScheduler::loop_, flush_tasks->loop);
95
15003
    while (std::unique_ptr<Task> task = scheduler->tasks_.Pop())
96
10002
      task->Run();
97
5001
  }
98
99
9856
  class StopTask : public Task {
100
   public:
101
4928
    explicit StopTask(DelayedTaskScheduler* scheduler): scheduler_(scheduler) {}
102
103
4928
    void Run() override {
104
9856
      std::vector<uv_timer_t*> timers;
105
5000
      for (uv_timer_t* timer : scheduler_->timers_)
106
72
        timers.push_back(timer);
107
5000
      for (uv_timer_t* timer : timers)
108
72
        scheduler_->TakeTimerTask(timer);
109
9856
      uv_close(reinterpret_cast<uv_handle_t*>(&scheduler_->flush_tasks_),
110
19712
               [](uv_handle_t* handle) {});
111
4928
    }
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
4935
WorkerThreadsTaskRunner::WorkerThreadsTaskRunner(int thread_pool_size) {
167
9870
  Mutex platform_workers_mutex;
168
9870
  ConditionVariable platform_workers_ready;
169
170
9870
  Mutex::ScopedLock lock(platform_workers_mutex);
171
4935
  int pending_platform_workers = thread_pool_size;
172
173
9870
  delayed_task_scheduler_ = std::make_unique<DelayedTaskScheduler>(
174
14805
      &pending_worker_tasks_);
175
4935
  threads_.push_back(delayed_task_scheduler_->Start());
176
177
24681
  for (int i = 0; i < thread_pool_size; i++) {
178
    PlatformWorkerData* worker_data = new PlatformWorkerData{
179
19746
      &pending_worker_tasks_, &platform_workers_mutex,
180
      &platform_workers_ready, &pending_platform_workers, i
181
39492
    };
182
39492
    std::unique_ptr<uv_thread_t> t { new uv_thread_t() };
183
19746
    if (uv_thread_create(t.get(), PlatformWorkerThread,
184
                         worker_data) != 0) {
185
      break;
186
    }
187
19746
    threads_.push_back(std::move(t));
188
  }
189
190
  // Wait for platform workers to initialize before continuing with the
191
  // bootstrap.
192
38509
  while (pending_platform_workers > 0) {
193
16787
    platform_workers_ready.Wait(lock);
194
  }
195
4935
}
196
197
75021
void WorkerThreadsTaskRunner::PostTask(std::unique_ptr<Task> task) {
198
75021
  pending_worker_tasks_.Push(std::move(task));
199
75020
}
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
12259
void WorkerThreadsTaskRunner::BlockingDrain() {
207
12259
  pending_worker_tasks_.BlockingDrain();
208
12259
}
209
210
4928
void WorkerThreadsTaskRunner::Shutdown() {
211
4928
  pending_worker_tasks_.Stop();
212
4928
  delayed_task_scheduler_->Stop();
213
29574
  for (size_t i = 0; i < threads_.size(); i++) {
214
24646
    CHECK_EQ(0, uv_thread_join(threads_[i].get()));
215
  }
216
4928
}
217
218
5006
int WorkerThreadsTaskRunner::NumberOfWorkerThreads() const {
219
5006
  return threads_.size();
220
}
221
222
5334
PerIsolatePlatformData::PerIsolatePlatformData(
223
5334
    Isolate* isolate, uv_loop_t* loop)
224
5334
  : isolate_(isolate), loop_(loop) {
225
5334
  flush_tasks_ = new uv_async_t();
226
5334
  CHECK_EQ(0, uv_async_init(loop, flush_tasks_, FlushTasks));
227
5334
  flush_tasks_->data = static_cast<void*>(this);
228
5334
  uv_unref(reinterpret_cast<uv_handle_t*>(flush_tasks_));
229
5334
}
230
231
std::shared_ptr<v8::TaskRunner>
232
27856
PerIsolatePlatformData::GetForegroundTaskRunner() {
233
27856
  return shared_from_this();
234
}
235
236
6933
void PerIsolatePlatformData::FlushTasks(uv_async_t* handle) {
237
6933
  auto platform_data = static_cast<PerIsolatePlatformData*>(handle->data);
238
6933
  platform_data->FlushForegroundTasksInternal();
239
6933
}
240
241
void PerIsolatePlatformData::PostIdleTask(std::unique_ptr<v8::IdleTask> task) {
242
  UNREACHABLE();
243
}
244
245
6595
void PerIsolatePlatformData::PostTask(std::unique_ptr<Task> task) {
246
6595
  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
6595
  foreground_tasks_.Push(std::move(task));
252
6595
  uv_async_send(flush_tasks_);
253
}
254
255
5130
void PerIsolatePlatformData::PostDelayedTask(
256
    std::unique_ptr<Task> task, double delay_in_seconds) {
257
5130
  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
10260
  std::unique_ptr<DelayedTask> delayed(new DelayedTask());
263
5130
  delayed->task = std::move(task);
264
5130
  delayed->platform_data = shared_from_this();
265
5130
  delayed->timeout = delay_in_seconds;
266
5130
  foreground_delayed_tasks_.Push(std::move(delayed));
267
5130
  uv_async_send(flush_tasks_);
268
}
269
270
1231
void PerIsolatePlatformData::PostNonNestableTask(std::unique_ptr<Task> task) {
271
1231
  PostTask(std::move(task));
272
1231
}
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
822
PerIsolatePlatformData::~PerIsolatePlatformData() {
281
411
  CHECK(!flush_tasks_);
282
411
}
283
284
361
void PerIsolatePlatformData::AddShutdownCallback(void (*callback)(void*),
285
                                                 void* data) {
286
361
  shutdown_callbacks_.emplace_back(ShutdownCallback { callback, data });
287
361
}
288
289
4836
void PerIsolatePlatformData::Shutdown() {
290
4836
  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
4836
  foreground_delayed_tasks_.PopAll();
298
4836
  foreground_tasks_.PopAll();
299
4836
  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
4836
  self_reference_ = shared_from_this();
306
9672
  uv_close(reinterpret_cast<uv_handle_t*>(flush_tasks_),
307
5658
           [](uv_handle_t* handle) {
308
    std::unique_ptr<uv_async_t> flush_tasks {
309
822
        reinterpret_cast<uv_async_t*>(handle) };
310
    PerIsolatePlatformData* platform_data =
311
411
        static_cast<PerIsolatePlatformData*>(flush_tasks->data);
312
411
    platform_data->DecreaseHandleCount();
313
411
    platform_data->self_reference_.reset();
314
10494
  });
315
4836
  flush_tasks_ = nullptr;
316
}
317
318
791
void PerIsolatePlatformData::DecreaseHandleCount() {
319
791
  CHECK_GE(uv_handle_count_, 1);
320
791
  if (--uv_handle_count_ == 0) {
321
772
    for (const auto& callback : shutdown_callbacks_)
322
361
      callback.cb(callback.data);
323
  }
324
791
}
325
326
4935
NodePlatform::NodePlatform(int thread_pool_size,
327
4935
                           v8::TracingController* tracing_controller) {
328
4935
  if (tracing_controller != nullptr) {
329
4928
    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
4935
  SetTracingController(tracing_controller_);
337
  DCHECK_EQ(GetTracingController(), tracing_controller_);
338
  worker_thread_task_runner_ =
339
4935
      std::make_shared<WorkerThreadsTaskRunner>(thread_pool_size);
340
4935
}
341
342
14784
NodePlatform::~NodePlatform() {
343
4928
  Shutdown();
344
9856
}
345
346
5333
void NodePlatform::RegisterIsolate(Isolate* isolate, uv_loop_t* loop) {
347
10666
  Mutex::ScopedLock lock(per_isolate_mutex_);
348
10666
  auto delegate = std::make_shared<PerIsolatePlatformData>(isolate, loop);
349
5333
  IsolatePlatformDelegate* ptr = delegate.get();
350
  auto insertion = per_isolate_.emplace(
351
    isolate,
352
5333
    std::make_pair(ptr, std::move(delegate)));
353
5333
  CHECK(insertion.second);
354
5333
}
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
4836
void NodePlatform::UnregisterIsolate(Isolate* isolate) {
366
9672
  Mutex::ScopedLock lock(per_isolate_mutex_);
367
4836
  auto existing_it = per_isolate_.find(isolate);
368
4836
  CHECK_NE(existing_it, per_isolate_.end());
369
4836
  auto& existing = existing_it->second;
370
4836
  if (existing.second) {
371
4835
    existing.second->Shutdown();
372
  }
373
4836
  per_isolate_.erase(existing_it);
374
4836
}
375
376
361
void NodePlatform::AddIsolateFinishedCallback(Isolate* isolate,
377
                                              void (*cb)(void*), void* data) {
378
722
  Mutex::ScopedLock lock(per_isolate_mutex_);
379
361
  auto it = per_isolate_.find(isolate);
380
361
  if (it == per_isolate_.end()) {
381
    cb(data);
382
    return;
383
  }
384
361
  CHECK(it->second.second);
385
361
  it->second.second->AddShutdownCallback(cb, data);
386
}
387
388
9851
void NodePlatform::Shutdown() {
389
9851
  if (has_shut_down_) return;
390
4928
  has_shut_down_ = true;
391
4928
  worker_thread_task_runner_->Shutdown();
392
393
  {
394
9856
    Mutex::ScopedLock lock(per_isolate_mutex_);
395
4928
    per_isolate_.clear();
396
  }
397
}
398
399
5006
int NodePlatform::NumberOfWorkerThreads() {
400
5006
  return worker_thread_task_runner_->NumberOfWorkerThreads();
401
}
402
403
6369
void PerIsolatePlatformData::RunForegroundTask(std::unique_ptr<Task> task) {
404
6369
  DebugSealHandleScope scope(isolate_);
405
6369
  Environment* env = Environment::GetCurrent(isolate_);
406
6369
  if (env != nullptr) {
407
11273
    v8::HandleScope scope(isolate_);
408
5637
    InternalCallbackScope cb_scope(env, Object::New(isolate_), { 0, 0 },
409
16911
                                   InternalCallbackScope::kNoFlags);
410
5637
    task->Run();
411
  } else {
412
732
    task->Run();
413
  }
414
6368
}
415
416
24
void PerIsolatePlatformData::DeleteFromScheduledTasks(DelayedTask* task) {
417
  auto it = std::find_if(scheduled_delayed_tasks_.begin(),
418
                         scheduled_delayed_tasks_.end(),
419
48
                         [task](const DelayedTaskPointer& delayed) -> bool {
420
48
          return delayed.get() == task;
421
24
      });
422
24
  CHECK_NE(it, scheduled_delayed_tasks_.end());
423
24
  scheduled_delayed_tasks_.erase(it);
424
24
}
425
426
24
void PerIsolatePlatformData::RunForegroundTask(uv_timer_t* handle) {
427
24
  DelayedTask* delayed = ContainerOf(&DelayedTask::timer, handle);
428
24
  delayed->platform_data->RunForegroundTask(std::move(delayed->task));
429
24
  delayed->platform_data->DeleteFromScheduledTasks(delayed);
430
24
}
431
432
9572
void NodePlatform::DrainTasks(Isolate* isolate) {
433
19143
  std::shared_ptr<PerIsolatePlatformData> per_isolate = ForNodeIsolate(isolate);
434
9573
  if (!per_isolate) return;
435
436

12259
  do {
437
    // Worker tasks aren't associated with an Isolate.
438
12259
    worker_thread_task_runner_->BlockingDrain();
439
12259
  } while (per_isolate->FlushForegroundTasksInternal());
440
}
441
442
19196
bool PerIsolatePlatformData::FlushForegroundTasksInternal() {
443
19196
  bool did_work = false;
444
445
  while (std::unique_ptr<DelayedTask> delayed =
446
28928
      foreground_delayed_tasks_.Pop()) {
447
4866
    did_work = true;
448
4866
    uint64_t delay_millis = llround(delayed->timeout * 1000);
449
450
4866
    delayed->timer.data = static_cast<void*>(delayed.get());
451
4866
    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
4866
    uv_timer_start(&delayed->timer, RunForegroundTask, delay_millis, 0);
455
4866
    uv_unref(reinterpret_cast<uv_handle_t*>(&delayed->timer));
456
4866
    uv_handle_count_++;
457
458
9732
    scheduled_delayed_tasks_.emplace_back(delayed.release(),
459
14310
                                          [](DelayedTask* delayed) {
460
9444
      uv_close(reinterpret_cast<uv_handle_t*>(&delayed->timer),
461
5482
               [](uv_handle_t* handle) {
462
        std::unique_ptr<DelayedTask> task {
463
760
            static_cast<DelayedTask*>(handle->data) };
464
380
        task->platform_data->DecreaseHandleCount();
465
10204
      });
466
19176
    });
467
4866
  }
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
38390
  std::queue<std::unique_ptr<Task>> tasks = foreground_tasks_.PopAll();
472
31884
  while (!tasks.empty()) {
473
12689
    std::unique_ptr<Task> task = std::move(tasks.front());
474
6345
    tasks.pop();
475
6345
    did_work = true;
476
6345
    RunForegroundTask(std::move(task));
477
  }
478
38389
  return did_work;
479
}
480
481
75021
void NodePlatform::CallOnWorkerThread(std::unique_ptr<Task> task) {
482
75021
  worker_thread_task_runner_->PostTask(std::move(task));
483
75020
}
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
27856
IsolatePlatformDelegate* NodePlatform::ForIsolate(Isolate* isolate) {
493
55712
  Mutex::ScopedLock lock(per_isolate_mutex_);
494
55712
  auto data = per_isolate_[isolate];
495
27856
  CHECK_NOT_NULL(data.first);
496
55712
  return data.first;
497
}
498
499
std::shared_ptr<PerIsolatePlatformData>
500
9576
NodePlatform::ForNodeIsolate(Isolate* isolate) {
501
19153
  Mutex::ScopedLock lock(per_isolate_mutex_);
502
19154
  auto data = per_isolate_[isolate];
503
9577
  CHECK_NOT_NULL(data.first);
504
19154
  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
27856
NodePlatform::GetForegroundTaskRunner(Isolate* isolate) {
519
27856
  return ForIsolate(isolate)->GetForegroundTaskRunner();
520
}
521
522
1009563
double NodePlatform::MonotonicallyIncreasingTime() {
523
  // Convert nanos to seconds.
524
1009563
  return uv_hrtime() / 1e9;
525
}
526
527
22657738
double NodePlatform::CurrentClockTimeMillis() {
528
22657738
  return SystemClockTimeMillis();
529
}
530
531
310357
v8::TracingController* NodePlatform::GetTracingController() {
532
310357
  CHECK_NOT_NULL(tracing_controller_);
533
310357
  return tracing_controller_;
534
}
535
536
4935
Platform::StackTracePrinter NodePlatform::GetStackTracePrinter() {
537
4935
  return []() {
538
    fprintf(stderr, "\n");
539
    DumpBacktrace(stderr);
540
    fflush(stderr);
541
9870
  };
542
}
543
544
template <class T>
545
20538
TaskQueue<T>::TaskQueue()
546
    : lock_(), tasks_available_(), tasks_drained_(),
547
20538
      outstanding_tasks_(0), stopped_(false), task_queue_() { }
548
549
template <class T>
550
91748
void TaskQueue<T>::Push(std::unique_ptr<T> task) {
551
183496
  Mutex::ScopedLock scoped_lock(lock_);
552
91748
  outstanding_tasks_++;
553
91748
  task_queue_.push(std::move(task));
554
91748
  tasks_available_.Signal(scoped_lock);
555
91748
}
556
557
template <class T>
558
34064
std::unique_ptr<T> TaskQueue<T>::Pop() {
559
68128
  Mutex::ScopedLock scoped_lock(lock_);
560

34064
  if (task_queue_.empty()) {
561
24197
    return std::unique_ptr<T>(nullptr);
562
  }
563
19734
  std::unique_ptr<T> result = std::move(task_queue_.front());
564
9867
  task_queue_.pop();
565
9867
  return result;
566
}
567
568
template <class T>
569
94709
std::unique_ptr<T> TaskQueue<T>::BlockingPop() {
570
189446
  Mutex::ScopedLock scoped_lock(lock_);
571

269809
  while (task_queue_.empty() && !stopped_) {
572
87550
    tasks_available_.Wait(scoped_lock);
573
  }
574
94737
  if (stopped_) {
575
19718
    return std::unique_ptr<T>(nullptr);
576
  }
577
150038
  std::unique_ptr<T> result = std::move(task_queue_.front());
578
75019
  task_queue_.pop();
579
75019
  return result;
580
}
581
582
template <class T>
583
74846
void TaskQueue<T>::NotifyOfCompletion() {
584
149865
  Mutex::ScopedLock scoped_lock(lock_);
585
75019
  if (--outstanding_tasks_ == 0) {
586
39741
    tasks_drained_.Broadcast(scoped_lock);
587
  }
588
74991
}
589
590
template <class T>
591
12259
void TaskQueue<T>::BlockingDrain() {
592
24518
  Mutex::ScopedLock scoped_lock(lock_);
593
13515
  while (outstanding_tasks_ > 0) {
594
628
    tasks_drained_.Wait(scoped_lock);
595
  }
596
12259
}
597
598
template <class T>
599
4928
void TaskQueue<T>::Stop() {
600
9856
  Mutex::ScopedLock scoped_lock(lock_);
601
4928
  stopped_ = true;
602
4928
  tasks_available_.Broadcast(scoped_lock);
603
4928
}
604
605
template <class T>
606
28868
std::queue<std::unique_ptr<T>> TaskQueue<T>::PopAll() {
607
57734
  Mutex::ScopedLock scoped_lock(lock_);
608
28868
  std::queue<std::unique_ptr<T>> result;
609
28868
  result.swap(task_queue_);
610
57734
  return result;
611
}
612
613

14970
}  // namespace node