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: 359 374 96.0 %
Date: 2021-06-09 04:12:02 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
19107
static void PlatformWorkerThread(void* data) {
28
  std::unique_ptr<PlatformWorkerData>
29
38213
      worker_data(static_cast<PlatformWorkerData*>(data));
30
31
19130
  TaskQueue<Task>* pending_worker_tasks = worker_data->task_queue;
32
  TRACE_EVENT_METADATA1("__metadata", "thread_name", "name",
33
19106
                        "PlatformWorkerThread");
34
35
4805
  // Notify the main thread that the platform worker is ready.
36
19116
  {
37
38250
    Mutex::ScopedLock lock(*worker_data->platform_workers_mutex);
38
19134
    (*worker_data->pending_platform_workers)--;
39
19134
    worker_data->platform_workers_ready->Signal(lock);
40
  }
41
42
164673
  while (std::unique_ptr<Task> task = pending_worker_tasks->BlockingPop()) {
43
72744
    task->Run();
44
72784
    pending_worker_tasks->NotifyOfCompletion();
45
72773
  }
46
19106
}
47
48
}  // namespace
49
50
4775
class WorkerThreadsTaskRunner::DelayedTaskScheduler {
51
 public:
52
4782
  explicit DelayedTaskScheduler(TaskQueue<Task>* tasks)
53
4782
    : pending_worker_tasks_(tasks) {}
54
55
4782
  std::unique_ptr<uv_thread_t> Start() {
56
14346
    auto start_thread = [](void* data) {
57
4782
      static_cast<DelayedTaskScheduler*>(data)->Run();
58
14339
    };
59
4782
    std::unique_ptr<uv_thread_t> t { new uv_thread_t() };
60
4782
    uv_sem_init(&ready_, 0);
61
4782
    CHECK_EQ(0, uv_thread_create(t.get(), start_thread, this));
62
4782
    uv_sem_wait(&ready_);
63
4782
    uv_sem_destroy(&ready_);
64
4782
    return t;
65
  }
66
67
532
  void PostDelayedTask(std::unique_ptr<Task> task, double delay_in_seconds) {
68
1064
    tasks_.Push(std::make_unique<ScheduleTask>(this, std::move(task),
69
532
                                               delay_in_seconds));
70
532
    uv_async_send(&flush_tasks_);
71
532
  }
72
73
4775
  void Stop() {
74
4775
    tasks_.Push(std::make_unique<StopTask>(this));
75
4775
    uv_async_send(&flush_tasks_);
76
4775
  }
77
78
 private:
79
4782
  void Run() {
80
4782
    TRACE_EVENT_METADATA1("__metadata", "thread_name", "name",
81
                          "WorkerThreadsTaskRunner::DelayedTaskScheduler");
82
4782
    loop_.data = this;
83
4782
    CHECK_EQ(0, uv_loop_init(&loop_));
84
9564
    flush_tasks_.data = this;
85
4782
    CHECK_EQ(0, uv_async_init(&loop_, &flush_tasks_, FlushTasks));
86
4782
    uv_sem_post(&ready_);
87
88
4782
    uv_run(&loop_, UV_RUN_DEFAULT);
89
4775
    CheckedUvLoopClose(&loop_);
90
4775
  }
91
92
5307
  static void FlushTasks(uv_async_t* flush_tasks) {
93
    DelayedTaskScheduler* scheduler =
94
5307
        ContainerOf(&DelayedTaskScheduler::loop_, flush_tasks->loop);
95
15921
    while (std::unique_ptr<Task> task = scheduler->tasks_.Pop())
96
10614
      task->Run();
97
5307
  }
98
99
9550
  class StopTask : public Task {
100
   public:
101
4775
    explicit StopTask(DelayedTaskScheduler* scheduler): scheduler_(scheduler) {}
102
103
4775
    void Run() override {
104
9550
      std::vector<uv_timer_t*> timers;
105
5272
      for (uv_timer_t* timer : scheduler_->timers_)
106
497
        timers.push_back(timer);
107
5272
      for (uv_timer_t* timer : timers)
108
497
        scheduler_->TakeTimerTask(timer);
109
9550
      uv_close(reinterpret_cast<uv_handle_t*>(&scheduler_->flush_tasks_),
110
19100
               [](uv_handle_t* handle) {});
111
4775
    }
112
113
   private:
114
     DelayedTaskScheduler* scheduler_;
115
  };
116
117
1064
  class ScheduleTask : public Task {
118
   public:
119
532
    ScheduleTask(DelayedTaskScheduler* scheduler,
120
                 std::unique_ptr<Task> task,
121
                 double delay_in_seconds)
122
532
      : scheduler_(scheduler),
123
532
        task_(std::move(task)),
124
1064
        delay_in_seconds_(delay_in_seconds) {}
125
126
532
    void Run() override {
127
532
      uint64_t delay_millis = llround(delay_in_seconds_ * 1000);
128
1064
      std::unique_ptr<uv_timer_t> timer(new uv_timer_t());
129
532
      CHECK_EQ(0, uv_timer_init(&scheduler_->loop_, timer.get()));
130
532
      timer->data = task_.release();
131
532
      CHECK_EQ(0, uv_timer_start(timer.get(), RunTask, delay_millis, 0));
132
532
      scheduler_->timers_.insert(timer.release());
133
532
    }
134
135
   private:
136
    DelayedTaskScheduler* scheduler_;
137
    std::unique_ptr<Task> task_;
138
    double delay_in_seconds_;
139
  };
140
141
35
  static void RunTask(uv_timer_t* timer) {
142
    DelayedTaskScheduler* scheduler =
143
35
        ContainerOf(&DelayedTaskScheduler::loop_, timer->loop);
144
35
    scheduler->pending_worker_tasks_->Push(scheduler->TakeTimerTask(timer));
145
35
  }
146
147
532
  std::unique_ptr<Task> TakeTimerTask(uv_timer_t* timer) {
148
532
    std::unique_ptr<Task> task(static_cast<Task*>(timer->data));
149
532
    uv_timer_stop(timer);
150
2660
    uv_close(reinterpret_cast<uv_handle_t*>(timer), [](uv_handle_t* handle) {
151
532
      delete reinterpret_cast<uv_timer_t*>(handle);
152
2128
    });
153
532
    timers_.erase(timer);
154
532
    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
4782
WorkerThreadsTaskRunner::WorkerThreadsTaskRunner(int thread_pool_size) {
167
9564
  Mutex platform_workers_mutex;
168
9564
  ConditionVariable platform_workers_ready;
169
170
9564
  Mutex::ScopedLock lock(platform_workers_mutex);
171
4782
  int pending_platform_workers = thread_pool_size;
172
173
9564
  delayed_task_scheduler_ = std::make_unique<DelayedTaskScheduler>(
174
14346
      &pending_worker_tasks_);
175
4782
  threads_.push_back(delayed_task_scheduler_->Start());
176
177
23916
  for (int i = 0; i < thread_pool_size; i++) {
178
    PlatformWorkerData* worker_data = new PlatformWorkerData{
179
19134
      &pending_worker_tasks_, &platform_workers_mutex,
180
      &platform_workers_ready, &pending_platform_workers, i
181
38268
    };
182
38268
    std::unique_ptr<uv_thread_t> t { new uv_thread_t() };
183
19134
    if (uv_thread_create(t.get(), PlatformWorkerThread,
184
                         worker_data) != 0) {
185
      break;
186
    }
187
19134
    threads_.push_back(std::move(t));
188
  }
189
190
  // Wait for platform workers to initialize before continuing with the
191
  // bootstrap.
192
34158
  while (pending_platform_workers > 0) {
193
14688
    platform_workers_ready.Wait(lock);
194
  }
195
4782
}
196
197
72759
void WorkerThreadsTaskRunner::PostTask(std::unique_ptr<Task> task) {
198
72759
  pending_worker_tasks_.Push(std::move(task));
199
72760
}
200
201
532
void WorkerThreadsTaskRunner::PostDelayedTask(std::unique_ptr<Task> task,
202
                                              double delay_in_seconds) {
203
532
  delayed_task_scheduler_->PostDelayedTask(std::move(task), delay_in_seconds);
204
532
}
205
206
16165
void WorkerThreadsTaskRunner::BlockingDrain() {
207
16165
  pending_worker_tasks_.BlockingDrain();
208
16165
}
209
210
4775
void WorkerThreadsTaskRunner::Shutdown() {
211
4775
  pending_worker_tasks_.Stop();
212
4775
  delayed_task_scheduler_->Stop();
213
28656
  for (size_t i = 0; i < threads_.size(); i++) {
214
23881
    CHECK_EQ(0, uv_thread_join(threads_[i].get()));
215
  }
216
4775
}
217
218
42801
int WorkerThreadsTaskRunner::NumberOfWorkerThreads() const {
219
42801
  return threads_.size();
220
}
221
222
5260
PerIsolatePlatformData::PerIsolatePlatformData(
223
5260
    Isolate* isolate, uv_loop_t* loop)
224
5260
  : isolate_(isolate), loop_(loop) {
225
5260
  flush_tasks_ = new uv_async_t();
226
5260
  CHECK_EQ(0, uv_async_init(loop, flush_tasks_, FlushTasks));
227
5260
  flush_tasks_->data = static_cast<void*>(this);
228
5260
  uv_unref(reinterpret_cast<uv_handle_t*>(flush_tasks_));
229
5260
}
230
231
std::shared_ptr<v8::TaskRunner>
232
35269
PerIsolatePlatformData::GetForegroundTaskRunner() {
233
35269
  return shared_from_this();
234
}
235
236
9961
void PerIsolatePlatformData::FlushTasks(uv_async_t* handle) {
237
9961
  auto platform_data = static_cast<PerIsolatePlatformData*>(handle->data);
238
9961
  platform_data->FlushForegroundTasksInternal();
239
9961
}
240
241
void PerIsolatePlatformData::PostIdleTask(std::unique_ptr<v8::IdleTask> task) {
242
  UNREACHABLE();
243
}
244
245
14382
void PerIsolatePlatformData::PostTask(std::unique_ptr<Task> task) {
246
14382
  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
14382
  foreground_tasks_.Push(std::move(task));
252
14382
  uv_async_send(flush_tasks_);
253
}
254
255
4685
void PerIsolatePlatformData::PostDelayedTask(
256
    std::unique_ptr<Task> task, double delay_in_seconds) {
257
4685
  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
9370
  std::unique_ptr<DelayedTask> delayed(new DelayedTask());
263
4685
  delayed->task = std::move(task);
264
4685
  delayed->platform_data = shared_from_this();
265
4685
  delayed->timeout = delay_in_seconds;
266
4685
  foreground_delayed_tasks_.Push(std::move(delayed));
267
4685
  uv_async_send(flush_tasks_);
268
}
269
270
8262
void PerIsolatePlatformData::PostNonNestableTask(std::unique_ptr<Task> task) {
271
8262
  PostTask(std::move(task));
272
8262
}
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
980
PerIsolatePlatformData::~PerIsolatePlatformData() {
281
490
  CHECK(!flush_tasks_);
282
490
}
283
284
435
void PerIsolatePlatformData::AddShutdownCallback(void (*callback)(void*),
285
                                                 void* data) {
286
435
  shutdown_callbacks_.emplace_back(ShutdownCallback { callback, data });
287
435
}
288
289
4787
void PerIsolatePlatformData::Shutdown() {
290
4787
  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
4787
  foreground_delayed_tasks_.PopAll();
298
4787
  foreground_tasks_.PopAll();
299
4787
  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
4787
  self_reference_ = shared_from_this();
306
9574
  uv_close(reinterpret_cast<uv_handle_t*>(flush_tasks_),
307
5765
           [](uv_handle_t* handle) {
308
    std::unique_ptr<uv_async_t> flush_tasks {
309
979
        reinterpret_cast<uv_async_t*>(handle) };
310
    PerIsolatePlatformData* platform_data =
311
490
        static_cast<PerIsolatePlatformData*>(flush_tasks->data);
312
490
    platform_data->DecreaseHandleCount();
313
490
    platform_data->self_reference_.reset();
314
10553
  });
315
4787
  flush_tasks_ = nullptr;
316
}
317
318
951
void PerIsolatePlatformData::DecreaseHandleCount() {
319
951
  CHECK_GE(uv_handle_count_, 1);
320
951
  if (--uv_handle_count_ == 0) {
321
925
    for (const auto& callback : shutdown_callbacks_)
322
435
      callback.cb(callback.data);
323
  }
324
951
}
325
326
4782
NodePlatform::NodePlatform(int thread_pool_size,
327
                           v8::TracingController* tracing_controller,
328
4782
                           v8::PageAllocator* page_allocator) {
329
4782
  if (tracing_controller != nullptr) {
330
4775
    tracing_controller_ = tracing_controller;
331
  } else {
332
7
    tracing_controller_ = new v8::TracingController();
333
  }
334
335
  // V8 will default to its built in allocator if none is provided.
336
4782
  page_allocator_ = page_allocator;
337
338
  // TODO(addaleax): It's a bit icky that we use global state here, but we can't
339
  // really do anything about it unless V8 starts exposing a way to access the
340
  // current v8::Platform instance.
341
4782
  SetTracingController(tracing_controller_);
342
  DCHECK_EQ(GetTracingController(), tracing_controller_);
343
  worker_thread_task_runner_ =
344
4782
      std::make_shared<WorkerThreadsTaskRunner>(thread_pool_size);
345
4782
}
346
347
14325
NodePlatform::~NodePlatform() {
348
4775
  Shutdown();
349
9550
}
350
351
5258
void NodePlatform::RegisterIsolate(Isolate* isolate, uv_loop_t* loop) {
352
10517
  Mutex::ScopedLock lock(per_isolate_mutex_);
353
10518
  auto delegate = std::make_shared<PerIsolatePlatformData>(isolate, loop);
354
5259
  IsolatePlatformDelegate* ptr = delegate.get();
355
  auto insertion = per_isolate_.emplace(
356
    isolate,
357
5259
    std::make_pair(ptr, std::move(delegate)));
358
5259
  CHECK(insertion.second);
359
5259
}
360
361
1
void NodePlatform::RegisterIsolate(Isolate* isolate,
362
                                   IsolatePlatformDelegate* delegate) {
363
2
  Mutex::ScopedLock lock(per_isolate_mutex_);
364
  auto insertion = per_isolate_.emplace(
365
    isolate,
366
1
    std::make_pair(delegate, std::shared_ptr<PerIsolatePlatformData>{}));
367
1
  CHECK(insertion.second);
368
1
}
369
370
4787
void NodePlatform::UnregisterIsolate(Isolate* isolate) {
371
9574
  Mutex::ScopedLock lock(per_isolate_mutex_);
372
4787
  auto existing_it = per_isolate_.find(isolate);
373
4787
  CHECK_NE(existing_it, per_isolate_.end());
374
4787
  auto& existing = existing_it->second;
375
4787
  if (existing.second) {
376
4786
    existing.second->Shutdown();
377
  }
378
4787
  per_isolate_.erase(existing_it);
379
4787
}
380
381
434
void NodePlatform::AddIsolateFinishedCallback(Isolate* isolate,
382
                                              void (*cb)(void*), void* data) {
383
869
  Mutex::ScopedLock lock(per_isolate_mutex_);
384
435
  auto it = per_isolate_.find(isolate);
385
435
  if (it == per_isolate_.end()) {
386
    cb(data);
387
    return;
388
  }
389
435
  CHECK(it->second.second);
390
435
  it->second.second->AddShutdownCallback(cb, data);
391
}
392
393
9545
void NodePlatform::Shutdown() {
394
9545
  if (has_shut_down_) return;
395
4775
  has_shut_down_ = true;
396
4775
  worker_thread_task_runner_->Shutdown();
397
398
  {
399
9550
    Mutex::ScopedLock lock(per_isolate_mutex_);
400
4775
    per_isolate_.clear();
401
  }
402
}
403
404
42801
int NodePlatform::NumberOfWorkerThreads() {
405
42801
  return worker_thread_task_runner_->NumberOfWorkerThreads();
406
}
407
408
14138
void PerIsolatePlatformData::RunForegroundTask(std::unique_ptr<Task> task) {
409
14138
  DebugSealHandleScope scope(isolate_);
410
14138
  Environment* env = Environment::GetCurrent(isolate_);
411
14138
  if (env != nullptr) {
412
24487
    v8::HandleScope scope(isolate_);
413
12247
    InternalCallbackScope cb_scope(env, Object::New(isolate_), { 0, 0 },
414
36741
                                   InternalCallbackScope::kNoFlags);
415
12247
    task->Run();
416
  } else {
417
    // The task is moved out of InternalCallbackScope if env is not available.
418
    // This is a required else block, and should not be removed.
419
    // See comment: https://github.com/nodejs/node/pull/34688#pullrequestreview-463867489
420
1891
    task->Run();
421
  }
422
14131
}
423
424
5
void PerIsolatePlatformData::DeleteFromScheduledTasks(DelayedTask* task) {
425
  auto it = std::find_if(scheduled_delayed_tasks_.begin(),
426
                         scheduled_delayed_tasks_.end(),
427
10
                         [task](const DelayedTaskPointer& delayed) -> bool {
428
10
          return delayed.get() == task;
429
5
      });
430
5
  CHECK_NE(it, scheduled_delayed_tasks_.end());
431
5
  scheduled_delayed_tasks_.erase(it);
432
5
}
433
434
5
void PerIsolatePlatformData::RunForegroundTask(uv_timer_t* handle) {
435
5
  DelayedTask* delayed = ContainerOf(&DelayedTask::timer, handle);
436
5
  delayed->platform_data->RunForegroundTask(std::move(delayed->task));
437
5
  delayed->platform_data->DeleteFromScheduledTasks(delayed);
438
5
}
439
440
9454
void NodePlatform::DrainTasks(Isolate* isolate) {
441
18899
  std::shared_ptr<PerIsolatePlatformData> per_isolate = ForNodeIsolate(isolate);
442
9454
  if (!per_isolate) return;
443
444

16165
  do {
445
    // Worker tasks aren't associated with an Isolate.
446
16165
    worker_thread_task_runner_->BlockingDrain();
447
16165
  } while (per_isolate->FlushForegroundTasksInternal());
448
}
449
450
26130
bool PerIsolatePlatformData::FlushForegroundTasksInternal() {
451
26130
  bool did_work = false;
452
453
  while (std::unique_ptr<DelayedTask> delayed =
454
35174
      foreground_delayed_tasks_.Pop()) {
455
4522
    did_work = true;
456
4522
    uint64_t delay_millis = llround(delayed->timeout * 1000);
457
458
4522
    delayed->timer.data = static_cast<void*>(delayed.get());
459
4522
    uv_timer_init(loop_, &delayed->timer);
460
    // Timers may not guarantee queue ordering of events with the same delay if
461
    // the delay is non-zero. This should not be a problem in practice.
462
4522
    uv_timer_start(&delayed->timer, RunForegroundTask, delay_millis, 0);
463
4522
    uv_unref(reinterpret_cast<uv_handle_t*>(&delayed->timer));
464
4522
    uv_handle_count_++;
465
466
9044
    scheduled_delayed_tasks_.emplace_back(delayed.release(),
467
13266
                                          [](DelayedTask* delayed) {
468
8744
      uv_close(reinterpret_cast<uv_handle_t*>(&delayed->timer),
469
5296
               [](uv_handle_t* handle) {
470
        std::unique_ptr<DelayedTask> task {
471
924
            static_cast<DelayedTask*>(handle->data) };
472
462
        task->platform_data->DecreaseHandleCount();
473
9668
      });
474
17788
    });
475
4522
  }
476
  // Move all foreground tasks into a separate queue and flush that queue.
477
  // This way tasks that are posted while flushing the queue will be run on the
478
  // next call of FlushForegroundTasksInternal.
479
52253
  std::queue<std::unique_ptr<Task>> tasks = foreground_tasks_.PopAll();
480
54382
  while (!tasks.empty()) {
481
28259
    std::unique_ptr<Task> task = std::move(tasks.front());
482
14133
    tasks.pop();
483
14133
    did_work = true;
484
14133
    RunForegroundTask(std::move(task));
485
  }
486
52246
  return did_work;
487
}
488
489
72760
void NodePlatform::CallOnWorkerThread(std::unique_ptr<Task> task) {
490
72760
  worker_thread_task_runner_->PostTask(std::move(task));
491
72760
}
492
493
532
void NodePlatform::CallDelayedOnWorkerThread(std::unique_ptr<Task> task,
494
                                             double delay_in_seconds) {
495
1064
  worker_thread_task_runner_->PostDelayedTask(std::move(task),
496
532
                                              delay_in_seconds);
497
532
}
498
499
500
35269
IsolatePlatformDelegate* NodePlatform::ForIsolate(Isolate* isolate) {
501
70538
  Mutex::ScopedLock lock(per_isolate_mutex_);
502
70538
  auto data = per_isolate_[isolate];
503
35269
  CHECK_NOT_NULL(data.first);
504
70538
  return data.first;
505
}
506
507
std::shared_ptr<PerIsolatePlatformData>
508
9458
NodePlatform::ForNodeIsolate(Isolate* isolate) {
509
18916
  Mutex::ScopedLock lock(per_isolate_mutex_);
510
18916
  auto data = per_isolate_[isolate];
511
9458
  CHECK_NOT_NULL(data.first);
512
18916
  return data.second;
513
}
514
515
4
bool NodePlatform::FlushForegroundTasks(Isolate* isolate) {
516
8
  std::shared_ptr<PerIsolatePlatformData> per_isolate = ForNodeIsolate(isolate);
517
4
  if (!per_isolate) return false;
518
4
  return per_isolate->FlushForegroundTasksInternal();
519
}
520
521
19228
std::unique_ptr<v8::JobHandle> NodePlatform::PostJob(v8::TaskPriority priority,
522
                                       std::unique_ptr<v8::JobTask> job_task) {
523
  return v8::platform::NewDefaultJobHandle(
524
19228
      this, priority, std::move(job_task), NumberOfWorkerThreads());
525
}
526
527
bool NodePlatform::IdleTasksEnabled(Isolate* isolate) {
528
  return ForIsolate(isolate)->IdleTasksEnabled();
529
}
530
531
std::shared_ptr<v8::TaskRunner>
532
35269
NodePlatform::GetForegroundTaskRunner(Isolate* isolate) {
533
35269
  return ForIsolate(isolate)->GetForegroundTaskRunner();
534
}
535
536
208654
double NodePlatform::MonotonicallyIncreasingTime() {
537
  // Convert nanos to seconds.
538
208654
  return uv_hrtime() / 1e9;
539
}
540
541
17547678
double NodePlatform::CurrentClockTimeMillis() {
542
17547678
  return SystemClockTimeMillis();
543
}
544
545
312439
v8::TracingController* NodePlatform::GetTracingController() {
546
312439
  CHECK_NOT_NULL(tracing_controller_);
547
312439
  return tracing_controller_;
548
}
549
550
4782
Platform::StackTracePrinter NodePlatform::GetStackTracePrinter() {
551
4782
  return []() {
552
    fprintf(stderr, "\n");
553
    DumpBacktrace(stderr);
554
    fflush(stderr);
555
9564
  };
556
}
557
558
4776
v8::PageAllocator* NodePlatform::GetPageAllocator() {
559
4776
  return page_allocator_;
560
}
561
562
template <class T>
563
20084
TaskQueue<T>::TaskQueue()
564
    : lock_(), tasks_available_(), tasks_drained_(),
565
20084
      outstanding_tasks_(0), stopped_(false), task_queue_() { }
566
567
template <class T>
568
97168
void TaskQueue<T>::Push(std::unique_ptr<T> task) {
569
194337
  Mutex::ScopedLock scoped_lock(lock_);
570
97169
  outstanding_tasks_++;
571
97169
  task_queue_.push(std::move(task));
572
97169
  tasks_available_.Signal(scoped_lock);
573
97169
}
574
575
template <class T>
576
41266
std::unique_ptr<T> TaskQueue<T>::Pop() {
577
82532
  Mutex::ScopedLock scoped_lock(lock_);
578

41266
  if (task_queue_.empty()) {
579
31437
    return std::unique_ptr<T>(nullptr);
580
  }
581
19658
  std::unique_ptr<T> result = std::move(task_queue_.front());
582
9829
  task_queue_.pop();
583
9829
  return result;
584
}
585
586
template <class T>
587
91890
std::unique_ptr<T> TaskQueue<T>::BlockingPop() {
588
183791
  Mutex::ScopedLock scoped_lock(lock_);
589

261421
  while (task_queue_.empty() && !stopped_) {
590
84774
    tasks_available_.Wait(scoped_lock);
591
  }
592
91901
  if (stopped_) {
593
19106
    return std::unique_ptr<T>(nullptr);
594
  }
595
145590
  std::unique_ptr<T> result = std::move(task_queue_.front());
596
72795
  task_queue_.pop();
597
72795
  return result;
598
}
599
600
template <class T>
601
72783
void TaskQueue<T>::NotifyOfCompletion() {
602
145578
  Mutex::ScopedLock scoped_lock(lock_);
603
72795
  if (--outstanding_tasks_ == 0) {
604
33464
    tasks_drained_.Broadcast(scoped_lock);
605
  }
606
72791
}
607
608
template <class T>
609
16165
void TaskQueue<T>::BlockingDrain() {
610
32330
  Mutex::ScopedLock scoped_lock(lock_);
611
17833
  while (outstanding_tasks_ > 0) {
612
834
    tasks_drained_.Wait(scoped_lock);
613
  }
614
16165
}
615
616
template <class T>
617
4775
void TaskQueue<T>::Stop() {
618
9550
  Mutex::ScopedLock scoped_lock(lock_);
619
4775
  stopped_ = true;
620
4775
  tasks_available_.Broadcast(scoped_lock);
621
4775
}
622
623
template <class T>
624
35704
std::queue<std::unique_ptr<T>> TaskQueue<T>::PopAll() {
625
71408
  Mutex::ScopedLock scoped_lock(lock_);
626
35704
  std::queue<std::unique_ptr<T>> result;
627
35704
  result.swap(task_queue_);
628
71408
  return result;
629
}
630
631

14538
}  // namespace node