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-09-06 22:14:11 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
17538
static void PlatformWorkerThread(void* data) {
28
  std::unique_ptr<PlatformWorkerData>
29
35188
      worker_data(static_cast<PlatformWorkerData*>(data));
30
31
17621
  TaskQueue<Task>* pending_worker_tasks = worker_data->task_queue;
32

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

8836
    TRACE_EVENT_METADATA1("__metadata", "thread_name", "name",
81
                          "WorkerThreadsTaskRunner::DelayedTaskScheduler");
82
4418
    loop_.data = this;
83
4418
    CHECK_EQ(0, uv_loop_init(&loop_));
84
4418
    flush_tasks_.data = this;
85
4418
    CHECK_EQ(0, uv_async_init(&loop_, &flush_tasks_, FlushTasks));
86
4418
    uv_sem_post(&ready_);
87
88
4418
    uv_run(&loop_, UV_RUN_DEFAULT);
89
4411
    CheckedUvLoopClose(&loop_);
90
4411
  }
91
92
4846
  static void FlushTasks(uv_async_t* flush_tasks) {
93
    DelayedTaskScheduler* scheduler =
94
4846
        ContainerOf(&DelayedTaskScheduler::loop_, flush_tasks->loop);
95
14572
    while (std::unique_ptr<Task> task = scheduler->tasks_.Pop())
96
9726
      task->Run();
97
4846
  }
98
99
8822
  class StopTask : public Task {
100
   public:
101
4411
    explicit StopTask(DelayedTaskScheduler* scheduler): scheduler_(scheduler) {}
102
103
4411
    void Run() override {
104
8822
      std::vector<uv_timer_t*> timers;
105
4826
      for (uv_timer_t* timer : scheduler_->timers_)
106
415
        timers.push_back(timer);
107
4826
      for (uv_timer_t* timer : timers)
108
415
        scheduler_->TakeTimerTask(timer);
109
8822
      uv_close(reinterpret_cast<uv_handle_t*>(&scheduler_->flush_tasks_),
110
17644
               [](uv_handle_t* handle) {});
111
4411
    }
112
113
   private:
114
     DelayedTaskScheduler* scheduler_;
115
  };
116
117
904
  class ScheduleTask : public Task {
118
   public:
119
452
    ScheduleTask(DelayedTaskScheduler* scheduler,
120
                 std::unique_ptr<Task> task,
121
                 double delay_in_seconds)
122
452
      : scheduler_(scheduler),
123
452
        task_(std::move(task)),
124
904
        delay_in_seconds_(delay_in_seconds) {}
125
126
452
    void Run() override {
127
452
      uint64_t delay_millis = llround(delay_in_seconds_ * 1000);
128
904
      std::unique_ptr<uv_timer_t> timer(new uv_timer_t());
129
452
      CHECK_EQ(0, uv_timer_init(&scheduler_->loop_, timer.get()));
130
452
      timer->data = task_.release();
131
452
      CHECK_EQ(0, uv_timer_start(timer.get(), RunTask, delay_millis, 0));
132
452
      scheduler_->timers_.insert(timer.release());
133
452
    }
134
135
   private:
136
    DelayedTaskScheduler* scheduler_;
137
    std::unique_ptr<Task> task_;
138
    double delay_in_seconds_;
139
  };
140
141
37
  static void RunTask(uv_timer_t* timer) {
142
    DelayedTaskScheduler* scheduler =
143
37
        ContainerOf(&DelayedTaskScheduler::loop_, timer->loop);
144
37
    scheduler->pending_worker_tasks_->Push(scheduler->TakeTimerTask(timer));
145
37
  }
146
147
452
  std::unique_ptr<Task> TakeTimerTask(uv_timer_t* timer) {
148
452
    std::unique_ptr<Task> task(static_cast<Task*>(timer->data));
149
452
    uv_timer_stop(timer);
150
2260
    uv_close(reinterpret_cast<uv_handle_t*>(timer), [](uv_handle_t* handle) {
151
452
      delete reinterpret_cast<uv_timer_t*>(handle);
152
1808
    });
153
452
    timers_.erase(timer);
154
452
    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
4418
WorkerThreadsTaskRunner::WorkerThreadsTaskRunner(int thread_pool_size) {
167
8836
  Mutex platform_workers_mutex;
168
8836
  ConditionVariable platform_workers_ready;
169
170
8836
  Mutex::ScopedLock lock(platform_workers_mutex);
171
4418
  int pending_platform_workers = thread_pool_size;
172
173
8836
  delayed_task_scheduler_ = std::make_unique<DelayedTaskScheduler>(
174
13254
      &pending_worker_tasks_);
175
4418
  threads_.push_back(delayed_task_scheduler_->Start());
176
177
22096
  for (int i = 0; i < thread_pool_size; i++) {
178
    PlatformWorkerData* worker_data = new PlatformWorkerData{
179
17678
      &pending_worker_tasks_, &platform_workers_mutex,
180
      &platform_workers_ready, &pending_platform_workers, i
181
35356
    };
182
35356
    std::unique_ptr<uv_thread_t> t { new uv_thread_t() };
183
17678
    if (uv_thread_create(t.get(), PlatformWorkerThread,
184
                         worker_data) != 0) {
185
      break;
186
    }
187
17678
    threads_.push_back(std::move(t));
188
  }
189
190
  // Wait for platform workers to initialize before continuing with the
191
  // bootstrap.
192
34606
  while (pending_platform_workers > 0) {
193
15094
    platform_workers_ready.Wait(lock);
194
  }
195
4418
}
196
197
72438
void WorkerThreadsTaskRunner::PostTask(std::unique_ptr<Task> task) {
198
72438
  pending_worker_tasks_.Push(std::move(task));
199
72439
}
200
201
452
void WorkerThreadsTaskRunner::PostDelayedTask(std::unique_ptr<Task> task,
202
                                              double delay_in_seconds) {
203
452
  delayed_task_scheduler_->PostDelayedTask(std::move(task), delay_in_seconds);
204
452
}
205
206
10970
void WorkerThreadsTaskRunner::BlockingDrain() {
207
10970
  pending_worker_tasks_.BlockingDrain();
208
10970
}
209
210
4411
void WorkerThreadsTaskRunner::Shutdown() {
211
4411
  pending_worker_tasks_.Stop();
212
4411
  delayed_task_scheduler_->Stop();
213
26472
  for (size_t i = 0; i < threads_.size(); i++) {
214
22061
    CHECK_EQ(0, uv_thread_join(threads_[i].get()));
215
  }
216
4411
}
217
218
4496
int WorkerThreadsTaskRunner::NumberOfWorkerThreads() const {
219
4496
  return threads_.size();
220
}
221
222
4884
PerIsolatePlatformData::PerIsolatePlatformData(
223
4884
    Isolate* isolate, uv_loop_t* loop)
224
4884
  : isolate_(isolate), loop_(loop) {
225
4884
  flush_tasks_ = new uv_async_t();
226
4884
  CHECK_EQ(0, uv_async_init(loop, flush_tasks_, FlushTasks));
227
4884
  flush_tasks_->data = static_cast<void*>(this);
228
4884
  uv_unref(reinterpret_cast<uv_handle_t*>(flush_tasks_));
229
4884
}
230
231
std::shared_ptr<v8::TaskRunner>
232
26218
PerIsolatePlatformData::GetForegroundTaskRunner() {
233
26218
  return shared_from_this();
234
}
235
236
6293
void PerIsolatePlatformData::FlushTasks(uv_async_t* handle) {
237
6293
  auto platform_data = static_cast<PerIsolatePlatformData*>(handle->data);
238
6293
  platform_data->FlushForegroundTasksInternal();
239
6293
}
240
241
void PerIsolatePlatformData::PostIdleTask(std::unique_ptr<v8::IdleTask> task) {
242
  UNREACHABLE();
243
}
244
245
6758
void PerIsolatePlatformData::PostTask(std::unique_ptr<Task> task) {
246
6758
  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
6758
  foreground_tasks_.Push(std::move(task));
252
6758
  uv_async_send(flush_tasks_);
253
}
254
255
4331
void PerIsolatePlatformData::PostDelayedTask(
256
    std::unique_ptr<Task> task, double delay_in_seconds) {
257
4331
  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
8662
  std::unique_ptr<DelayedTask> delayed(new DelayedTask());
263
4331
  delayed->task = std::move(task);
264
4331
  delayed->platform_data = shared_from_this();
265
4331
  delayed->timeout = delay_in_seconds;
266
4331
  foreground_delayed_tasks_.Push(std::move(delayed));
267
4331
  uv_async_send(flush_tasks_);
268
}
269
270
1379
void PerIsolatePlatformData::PostNonNestableTask(std::unique_ptr<Task> task) {
271
1379
  PostTask(std::move(task));
272
1379
}
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
956
PerIsolatePlatformData::~PerIsolatePlatformData() {
281
478
  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
4417
void PerIsolatePlatformData::Shutdown() {
290
4417
  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
4417
  foreground_delayed_tasks_.PopAll();
298
4417
  foreground_tasks_.PopAll();
299
4417
  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
4417
  self_reference_ = shared_from_this();
306
8834
  uv_close(reinterpret_cast<uv_handle_t*>(flush_tasks_),
307
5373
           [](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
478
    platform_data->DecreaseHandleCount();
313
478
    platform_data->self_reference_.reset();
314
9790
  });
315
4417
  flush_tasks_ = nullptr;
316
}
317
318
923
void PerIsolatePlatformData::DecreaseHandleCount() {
319
923
  CHECK_GE(uv_handle_count_, 1);
320
923
  if (--uv_handle_count_ == 0) {
321
905
    for (const auto& callback : shutdown_callbacks_)
322
427
      callback.cb(callback.data);
323
  }
324
923
}
325
326
4418
NodePlatform::NodePlatform(int thread_pool_size,
327
4418
                           v8::TracingController* tracing_controller) {
328
4418
  if (tracing_controller != nullptr) {
329
4411
    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
4418
  SetTracingController(tracing_controller_);
337
  DCHECK_EQ(GetTracingController(), tracing_controller_);
338
  worker_thread_task_runner_ =
339
4418
      std::make_shared<WorkerThreadsTaskRunner>(thread_pool_size);
340
4418
}
341
342
13233
NodePlatform::~NodePlatform() {
343
4411
  Shutdown();
344
8822
}
345
346
4883
void NodePlatform::RegisterIsolate(Isolate* isolate, uv_loop_t* loop) {
347
9766
  Mutex::ScopedLock lock(per_isolate_mutex_);
348
9766
  auto delegate = std::make_shared<PerIsolatePlatformData>(isolate, loop);
349
4883
  IsolatePlatformDelegate* ptr = delegate.get();
350
  auto insertion = per_isolate_.emplace(
351
    isolate,
352
4883
    std::make_pair(ptr, std::move(delegate)));
353
4883
  CHECK(insertion.second);
354
4883
}
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
4417
void NodePlatform::UnregisterIsolate(Isolate* isolate) {
366
8834
  Mutex::ScopedLock lock(per_isolate_mutex_);
367
4417
  auto existing_it = per_isolate_.find(isolate);
368
4417
  CHECK_NE(existing_it, per_isolate_.end());
369
4417
  auto& existing = existing_it->second;
370
4417
  if (existing.second) {
371
4416
    existing.second->Shutdown();
372
  }
373
4417
  per_isolate_.erase(existing_it);
374
4417
}
375
376
423
void NodePlatform::AddIsolateFinishedCallback(Isolate* isolate,
377
                                              void (*cb)(void*), void* data) {
378
850
  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
8817
void NodePlatform::Shutdown() {
389
8817
  if (has_shut_down_) return;
390
4411
  has_shut_down_ = true;
391
4411
  worker_thread_task_runner_->Shutdown();
392
393
  {
394
8822
    Mutex::ScopedLock lock(per_isolate_mutex_);
395
4411
    per_isolate_.clear();
396
  }
397
}
398
399
4496
int NodePlatform::NumberOfWorkerThreads() {
400
4496
  return worker_thread_task_runner_->NumberOfWorkerThreads();
401
}
402
403
6520
void PerIsolatePlatformData::RunForegroundTask(std::unique_ptr<Task> task) {
404
6520
  DebugSealHandleScope scope(isolate_);
405
6520
  Environment* env = Environment::GetCurrent(isolate_);
406
6520
  if (env != nullptr) {
407
11709
    v8::HandleScope scope(isolate_);
408
5855
    InternalCallbackScope cb_scope(env, Object::New(isolate_), { 0, 0 },
409
17565
                                   InternalCallbackScope::kNoFlags);
410
5855
    task->Run();
411
  } else {
412
665
    task->Run();
413
  }
414
6519
}
415
416
22
void PerIsolatePlatformData::DeleteFromScheduledTasks(DelayedTask* task) {
417
  auto it = std::find_if(scheduled_delayed_tasks_.begin(),
418
                         scheduled_delayed_tasks_.end(),
419
44
                         [task](const DelayedTaskPointer& delayed) -> bool {
420
44
          return delayed.get() == task;
421
22
      });
422
22
  CHECK_NE(it, scheduled_delayed_tasks_.end());
423
22
  scheduled_delayed_tasks_.erase(it);
424
22
}
425
426
22
void PerIsolatePlatformData::RunForegroundTask(uv_timer_t* handle) {
427
22
  DelayedTask* delayed = ContainerOf(&DelayedTask::timer, handle);
428
22
  delayed->platform_data->RunForegroundTask(std::move(delayed->task));
429
22
  delayed->platform_data->DeleteFromScheduledTasks(delayed);
430
22
}
431
432
8729
void NodePlatform::DrainTasks(Isolate* isolate) {
433
17456
  std::shared_ptr<PerIsolatePlatformData> per_isolate = ForNodeIsolate(isolate);
434
8729
  if (!per_isolate) return;
435
436

10970
  do {
437
    // Worker tasks aren't associated with an Isolate.
438
10970
    worker_thread_task_runner_->BlockingDrain();
439
10970
  } while (per_isolate->FlushForegroundTasksInternal());
440
}
441
442
17267
bool PerIsolatePlatformData::FlushForegroundTasksInternal() {
443
17267
  bool did_work = false;
444
445
  while (std::unique_ptr<DelayedTask> delayed =
446
25533
      foreground_delayed_tasks_.Pop()) {
447
4133
    did_work = true;
448
4133
    uint64_t delay_millis = llround(delayed->timeout * 1000);
449
450
4133
    delayed->timer.data = static_cast<void*>(delayed.get());
451
4133
    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
4133
    uv_timer_start(&delayed->timer, RunForegroundTask, delay_millis, 0);
455
4133
    uv_unref(reinterpret_cast<uv_handle_t*>(&delayed->timer));
456
4133
    uv_handle_count_++;
457
458
8266
    scheduled_delayed_tasks_.emplace_back(delayed.release(),
459
12155
                                          [](DelayedTask* delayed) {
460
8022
      uv_close(reinterpret_cast<uv_handle_t*>(&delayed->timer),
461
4901
               [](uv_handle_t* handle) {
462
        std::unique_ptr<DelayedTask> task {
463
890
            static_cast<DelayedTask*>(handle->data) };
464
445
        task->platform_data->DecreaseHandleCount();
465
8912
      });
466
16288
    });
467
4133
  }
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
34533
  std::queue<std::unique_ptr<Task>> tasks = foreground_tasks_.PopAll();
472
30259
  while (!tasks.empty()) {
473
12995
    std::unique_ptr<Task> task = std::move(tasks.front());
474
6498
    tasks.pop();
475
6498
    did_work = true;
476
6498
    RunForegroundTask(std::move(task));
477
  }
478
34532
  return did_work;
479
}
480
481
72439
void NodePlatform::CallOnWorkerThread(std::unique_ptr<Task> task) {
482
72439
  worker_thread_task_runner_->PostTask(std::move(task));
483
72439
}
484
485
452
void NodePlatform::CallDelayedOnWorkerThread(std::unique_ptr<Task> task,
486
                                             double delay_in_seconds) {
487
904
  worker_thread_task_runner_->PostDelayedTask(std::move(task),
488
452
                                              delay_in_seconds);
489
452
}
490
491
492
26218
IsolatePlatformDelegate* NodePlatform::ForIsolate(Isolate* isolate) {
493
52436
  Mutex::ScopedLock lock(per_isolate_mutex_);
494
52436
  auto data = per_isolate_[isolate];
495
26218
  CHECK_NOT_NULL(data.first);
496
52436
  return data.first;
497
}
498
499
std::shared_ptr<PerIsolatePlatformData>
500
8733
NodePlatform::ForNodeIsolate(Isolate* isolate) {
501
17466
  Mutex::ScopedLock lock(per_isolate_mutex_);
502
17466
  auto data = per_isolate_[isolate];
503
8733
  CHECK_NOT_NULL(data.first);
504
17466
  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
26218
NodePlatform::GetForegroundTaskRunner(Isolate* isolate) {
519
26218
  return ForIsolate(isolate)->GetForegroundTaskRunner();
520
}
521
522
973919
double NodePlatform::MonotonicallyIncreasingTime() {
523
  // Convert nanos to seconds.
524
973919
  return uv_hrtime() / 1e9;
525
}
526
527
23876281
double NodePlatform::CurrentClockTimeMillis() {
528
23876281
  return SystemClockTimeMillis();
529
}
530
531
279112
v8::TracingController* NodePlatform::GetTracingController() {
532
279112
  CHECK_NOT_NULL(tracing_controller_);
533
279112
  return tracing_controller_;
534
}
535
536
4418
Platform::StackTracePrinter NodePlatform::GetStackTracePrinter() {
537
4418
  return []() {
538
    fprintf(stderr, "\n");
539
    DumpBacktrace(stderr);
540
    fflush(stderr);
541
8836
  };
542
}
543
544
template <class T>
545
18604
TaskQueue<T>::TaskQueue()
546
    : lock_(), tasks_available_(), tasks_drained_(),
547
18604
      outstanding_tasks_(0), stopped_(false), task_queue_() { }
548
549
template <class T>
550
88427
void TaskQueue<T>::Push(std::unique_ptr<T> task) {
551
176855
  Mutex::ScopedLock scoped_lock(lock_);
552
88428
  outstanding_tasks_++;
553
88428
  task_queue_.push(std::move(task));
554
88428
  tasks_available_.Signal(scoped_lock);
555
88428
}
556
557
template <class T>
558
31109
std::unique_ptr<T> TaskQueue<T>::Pop() {
559
62218
  Mutex::ScopedLock scoped_lock(lock_);
560

31109
  if (task_queue_.empty()) {
561
22113
    return std::unique_ptr<T>(nullptr);
562
  }
563
17992
  std::unique_ptr<T> result = std::move(task_queue_.front());
564
8996
  task_queue_.pop();
565
8996
  return result;
566
}
567
568
template <class T>
569
90130
std::unique_ptr<T> TaskQueue<T>::BlockingPop() {
570
180256
  Mutex::ScopedLock scoped_lock(lock_);
571

255950
  while (task_queue_.empty() && !stopped_) {
572
82926
    tasks_available_.Wait(scoped_lock);
573
  }
574
90126
  if (stopped_) {
575
17650
    return std::unique_ptr<T>(nullptr);
576
  }
577
144952
  std::unique_ptr<T> result = std::move(task_queue_.front());
578
72476
  task_queue_.pop();
579
72476
  return result;
580
}
581
582
template <class T>
583
72325
void TaskQueue<T>::NotifyOfCompletion() {
584
144801
  Mutex::ScopedLock scoped_lock(lock_);
585
72476
  if (--outstanding_tasks_ == 0) {
586
38242
    tasks_drained_.Broadcast(scoped_lock);
587
  }
588
72459
}
589
590
template <class T>
591
10970
void TaskQueue<T>::BlockingDrain() {
592
21940
  Mutex::ScopedLock scoped_lock(lock_);
593
12266
  while (outstanding_tasks_ > 0) {
594
648
    tasks_drained_.Wait(scoped_lock);
595
  }
596
10970
}
597
598
template <class T>
599
4411
void TaskQueue<T>::Stop() {
600
8822
  Mutex::ScopedLock scoped_lock(lock_);
601
4411
  stopped_ = true;
602
4411
  tasks_available_.Broadcast(scoped_lock);
603
4411
}
604
605
template <class T>
606
26101
std::queue<std::unique_ptr<T>> TaskQueue<T>::PopAll() {
607
52199
  Mutex::ScopedLock scoped_lock(lock_);
608
26101
  std::queue<std::unique_ptr<T>> result;
609
26101
  result.swap(task_queue_);
610
52199
  return result;
611
}
612
613

13419
}  // namespace node