GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_platform.cc Lines: 350 366 95.6 %
Date: 2022-04-17 04:15:01 Branches: 78 102 76.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
20082
static void PlatformWorkerThread(void* data) {
28
  std::unique_ptr<PlatformWorkerData>
29
40136
      worker_data(static_cast<PlatformWorkerData*>(data));
30
31
20082
  TaskQueue<Task>* pending_worker_tasks = worker_data->task_queue;
32

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

10090
    TRACE_EVENT_METADATA1("__metadata", "thread_name", "name",
81
                          "WorkerThreadsTaskRunner::DelayedTaskScheduler");
82
5019
    loop_.data = this;
83
5019
    CHECK_EQ(0, uv_loop_init(&loop_));
84
5019
    flush_tasks_.data = this;
85
5019
    CHECK_EQ(0, uv_async_init(&loop_, &flush_tasks_, FlushTasks));
86
5019
    uv_sem_post(&ready_);
87
88
5019
    uv_run(&loop_, UV_RUN_DEFAULT);
89
5012
    CheckedUvLoopClose(&loop_);
90
5012
  }
91
92
5539
  static void FlushTasks(uv_async_t* flush_tasks) {
93
    DelayedTaskScheduler* scheduler =
94
5539
        ContainerOf(&DelayedTaskScheduler::loop_, flush_tasks->loop);
95
11078
    while (std::unique_ptr<Task> task = scheduler->tasks_.Pop())
96
11078
      task->Run();
97
5539
  }
98
99
  class StopTask : public Task {
100
   public:
101
5012
    explicit StopTask(DelayedTaskScheduler* scheduler): scheduler_(scheduler) {}
102
103
5012
    void Run() override {
104
5012
      std::vector<uv_timer_t*> timers;
105
5371
      for (uv_timer_t* timer : scheduler_->timers_)
106
359
        timers.push_back(timer);
107
5371
      for (uv_timer_t* timer : timers)
108
359
        scheduler_->TakeTimerTask(timer);
109
5012
      uv_close(reinterpret_cast<uv_handle_t*>(&scheduler_->flush_tasks_),
110
5012
               [](uv_handle_t* handle) {});
111
5012
    }
112
113
   private:
114
     DelayedTaskScheduler* scheduler_;
115
  };
116
117
  class ScheduleTask : public Task {
118
   public:
119
527
    ScheduleTask(DelayedTaskScheduler* scheduler,
120
                 std::unique_ptr<Task> task,
121
                 double delay_in_seconds)
122
527
      : scheduler_(scheduler),
123
527
        task_(std::move(task)),
124
527
        delay_in_seconds_(delay_in_seconds) {}
125
126
527
    void Run() override {
127
527
      uint64_t delay_millis = llround(delay_in_seconds_ * 1000);
128
527
      std::unique_ptr<uv_timer_t> timer(new uv_timer_t());
129
527
      CHECK_EQ(0, uv_timer_init(&scheduler_->loop_, timer.get()));
130
527
      timer->data = task_.release();
131
527
      CHECK_EQ(0, uv_timer_start(timer.get(), RunTask, delay_millis, 0));
132
527
      scheduler_->timers_.insert(timer.release());
133
527
    }
134
135
   private:
136
    DelayedTaskScheduler* scheduler_;
137
    std::unique_ptr<Task> task_;
138
    double delay_in_seconds_;
139
  };
140
141
168
  static void RunTask(uv_timer_t* timer) {
142
    DelayedTaskScheduler* scheduler =
143
168
        ContainerOf(&DelayedTaskScheduler::loop_, timer->loop);
144
168
    scheduler->pending_worker_tasks_->Push(scheduler->TakeTimerTask(timer));
145
168
  }
146
147
527
  std::unique_ptr<Task> TakeTimerTask(uv_timer_t* timer) {
148
527
    std::unique_ptr<Task> task(static_cast<Task*>(timer->data));
149
527
    uv_timer_stop(timer);
150
527
    uv_close(reinterpret_cast<uv_handle_t*>(timer), [](uv_handle_t* handle) {
151
527
      delete reinterpret_cast<uv_timer_t*>(handle);
152
527
    });
153
527
    timers_.erase(timer);
154
527
    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
5019
WorkerThreadsTaskRunner::WorkerThreadsTaskRunner(int thread_pool_size) {
167
10038
  Mutex platform_workers_mutex;
168
10038
  ConditionVariable platform_workers_ready;
169
170
10038
  Mutex::ScopedLock lock(platform_workers_mutex);
171
5019
  int pending_platform_workers = thread_pool_size;
172
173
5019
  delayed_task_scheduler_ = std::make_unique<DelayedTaskScheduler>(
174
5019
      &pending_worker_tasks_);
175
5019
  threads_.push_back(delayed_task_scheduler_->Start());
176
177
25101
  for (int i = 0; i < thread_pool_size; i++) {
178
    PlatformWorkerData* worker_data = new PlatformWorkerData{
179
20082
      &pending_worker_tasks_, &platform_workers_mutex,
180
      &platform_workers_ready, &pending_platform_workers, i
181
20082
    };
182
20082
    std::unique_ptr<uv_thread_t> t { new uv_thread_t() };
183
20082
    if (uv_thread_create(t.get(), PlatformWorkerThread,
184
20082
                         worker_data) != 0) {
185
      break;
186
    }
187
20082
    threads_.push_back(std::move(t));
188
  }
189
190
  // Wait for platform workers to initialize before continuing with the
191
  // bootstrap.
192
23030
  while (pending_platform_workers > 0) {
193
18011
    platform_workers_ready.Wait(lock);
194
  }
195
5019
}
196
197
96205
void WorkerThreadsTaskRunner::PostTask(std::unique_ptr<Task> task) {
198
96205
  pending_worker_tasks_.Push(std::move(task));
199
96205
}
200
201
527
void WorkerThreadsTaskRunner::PostDelayedTask(std::unique_ptr<Task> task,
202
                                              double delay_in_seconds) {
203
527
  delayed_task_scheduler_->PostDelayedTask(std::move(task), delay_in_seconds);
204
527
}
205
206
14258
void WorkerThreadsTaskRunner::BlockingDrain() {
207
14258
  pending_worker_tasks_.BlockingDrain();
208
14258
}
209
210
5012
void WorkerThreadsTaskRunner::Shutdown() {
211
5012
  pending_worker_tasks_.Stop();
212
5012
  delayed_task_scheduler_->Stop();
213
30078
  for (size_t i = 0; i < threads_.size(); i++) {
214
25066
    CHECK_EQ(0, uv_thread_join(threads_[i].get()));
215
  }
216
5012
}
217
218
57520
int WorkerThreadsTaskRunner::NumberOfWorkerThreads() const {
219
57520
  return threads_.size();
220
}
221
222
5663
PerIsolatePlatformData::PerIsolatePlatformData(
223
5663
    Isolate* isolate, uv_loop_t* loop)
224
5663
  : isolate_(isolate), loop_(loop) {
225
5663
  flush_tasks_ = new uv_async_t();
226
5663
  CHECK_EQ(0, uv_async_init(loop, flush_tasks_, FlushTasks));
227
5663
  flush_tasks_->data = static_cast<void*>(this);
228
5663
  uv_unref(reinterpret_cast<uv_handle_t*>(flush_tasks_));
229
5663
}
230
231
std::shared_ptr<v8::TaskRunner>
232
26133
PerIsolatePlatformData::GetForegroundTaskRunner() {
233
26133
  return shared_from_this();
234
}
235
236
7972
void PerIsolatePlatformData::FlushTasks(uv_async_t* handle) {
237
7972
  auto platform_data = static_cast<PerIsolatePlatformData*>(handle->data);
238
7972
  platform_data->FlushForegroundTasksInternal();
239
7972
}
240
241
void PerIsolatePlatformData::PostIdleTask(std::unique_ptr<v8::IdleTask> task) {
242
  UNREACHABLE();
243
}
244
245
9337
void PerIsolatePlatformData::PostTask(std::unique_ptr<Task> task) {
246
9337
  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
9337
  foreground_tasks_.Push(std::move(task));
252
9337
  uv_async_send(flush_tasks_);
253
}
254
255
5194
void PerIsolatePlatformData::PostDelayedTask(
256
    std::unique_ptr<Task> task, double delay_in_seconds) {
257
5194
  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
10388
  std::unique_ptr<DelayedTask> delayed(new DelayedTask());
263
5194
  delayed->task = std::move(task);
264
5194
  delayed->platform_data = shared_from_this();
265
5194
  delayed->timeout = delay_in_seconds;
266
5194
  foreground_delayed_tasks_.Push(std::move(delayed));
267
5194
  uv_async_send(flush_tasks_);
268
}
269
270
1911
void PerIsolatePlatformData::PostNonNestableTask(std::unique_ptr<Task> task) {
271
1911
  PostTask(std::move(task));
272
1911
}
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
1300
PerIsolatePlatformData::~PerIsolatePlatformData() {
281
1300
  CHECK(!flush_tasks_);
282
}
283
284
592
void PerIsolatePlatformData::AddShutdownCallback(void (*callback)(void*),
285
                                                 void* data) {
286
592
  shutdown_callbacks_.emplace_back(ShutdownCallback { callback, data });
287
592
}
288
289
5165
void PerIsolatePlatformData::Shutdown() {
290
5165
  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
5165
  foreground_delayed_tasks_.PopAll();
298
5165
  foreground_tasks_.PopAll();
299
5165
  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
5165
  self_reference_ = shared_from_this();
306
5165
  uv_close(reinterpret_cast<uv_handle_t*>(flush_tasks_),
307
650
           [](uv_handle_t* handle) {
308
    std::unique_ptr<uv_async_t> flush_tasks {
309
1300
        reinterpret_cast<uv_async_t*>(handle) };
310
    PerIsolatePlatformData* platform_data =
311
650
        static_cast<PerIsolatePlatformData*>(flush_tasks->data);
312
650
    platform_data->DecreaseHandleCount();
313
650
    platform_data->self_reference_.reset();
314
650
  });
315
5165
  flush_tasks_ = nullptr;
316
}
317
318
1273
void PerIsolatePlatformData::DecreaseHandleCount() {
319
1273
  CHECK_GE(uv_handle_count_, 1);
320
1273
  if (--uv_handle_count_ == 0) {
321
1242
    for (const auto& callback : shutdown_callbacks_)
322
592
      callback.cb(callback.data);
323
  }
324
1273
}
325
326
5019
NodePlatform::NodePlatform(int thread_pool_size,
327
                           v8::TracingController* tracing_controller,
328
5019
                           v8::PageAllocator* page_allocator) {
329
5019
  if (tracing_controller != nullptr) {
330
5012
    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
5019
  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
5019
  SetTracingController(tracing_controller_);
342
  DCHECK_EQ(GetTracingController(), tracing_controller_);
343
  worker_thread_task_runner_ =
344
5019
      std::make_shared<WorkerThreadsTaskRunner>(thread_pool_size);
345
5019
}
346
347
20048
NodePlatform::~NodePlatform() {
348
10024
  Shutdown();
349
20048
}
350
351
5662
void NodePlatform::RegisterIsolate(Isolate* isolate, uv_loop_t* loop) {
352
11324
  Mutex::ScopedLock lock(per_isolate_mutex_);
353
11324
  auto delegate = std::make_shared<PerIsolatePlatformData>(isolate, loop);
354
5662
  IsolatePlatformDelegate* ptr = delegate.get();
355
  auto insertion = per_isolate_.emplace(
356
    isolate,
357
5662
    std::make_pair(ptr, std::move(delegate)));
358
5662
  CHECK(insertion.second);
359
5662
}
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
5165
void NodePlatform::UnregisterIsolate(Isolate* isolate) {
371
10330
  Mutex::ScopedLock lock(per_isolate_mutex_);
372
5165
  auto existing_it = per_isolate_.find(isolate);
373
5165
  CHECK_NE(existing_it, per_isolate_.end());
374
5165
  auto& existing = existing_it->second;
375
5165
  if (existing.second) {
376
5164
    existing.second->Shutdown();
377
  }
378
5165
  per_isolate_.erase(existing_it);
379
5165
}
380
381
592
void NodePlatform::AddIsolateFinishedCallback(Isolate* isolate,
382
                                              void (*cb)(void*), void* data) {
383
592
  Mutex::ScopedLock lock(per_isolate_mutex_);
384
592
  auto it = per_isolate_.find(isolate);
385
592
  if (it == per_isolate_.end()) {
386
    cb(data);
387
    return;
388
  }
389
592
  CHECK(it->second.second);
390
592
  it->second.second->AddShutdownCallback(cb, data);
391
}
392
393
10019
void NodePlatform::Shutdown() {
394
10019
  if (has_shut_down_) return;
395
5012
  has_shut_down_ = true;
396
5012
  worker_thread_task_runner_->Shutdown();
397
398
  {
399
10024
    Mutex::ScopedLock lock(per_isolate_mutex_);
400
5012
    per_isolate_.clear();
401
  }
402
}
403
404
57520
int NodePlatform::NumberOfWorkerThreads() {
405
57520
  return worker_thread_task_runner_->NumberOfWorkerThreads();
406
}
407
408
8980
void PerIsolatePlatformData::RunForegroundTask(std::unique_ptr<Task> task) {
409
8980
  DebugSealHandleScope scope(isolate_);
410
8980
  Environment* env = Environment::GetCurrent(isolate_);
411
8980
  if (env != nullptr) {
412
13675
    v8::HandleScope scope(isolate_);
413
6841
    InternalCallbackScope cb_scope(env, Object::New(isolate_), { 0, 0 },
414
13682
                                   InternalCallbackScope::kNoFlags);
415
6841
    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
2139
    task->Run();
421
  }
422
8973
}
423
424
7
void PerIsolatePlatformData::DeleteFromScheduledTasks(DelayedTask* task) {
425
  auto it = std::find_if(scheduled_delayed_tasks_.begin(),
426
                         scheduled_delayed_tasks_.end(),
427
14
                         [task](const DelayedTaskPointer& delayed) -> bool {
428
7
          return delayed.get() == task;
429
7
      });
430
7
  CHECK_NE(it, scheduled_delayed_tasks_.end());
431
7
  scheduled_delayed_tasks_.erase(it);
432
7
}
433
434
7
void PerIsolatePlatformData::RunForegroundTask(uv_timer_t* handle) {
435
7
  DelayedTask* delayed = ContainerOf(&DelayedTask::timer, handle);
436
7
  delayed->platform_data->RunForegroundTask(std::move(delayed->task));
437
7
  delayed->platform_data->DeleteFromScheduledTasks(delayed);
438
7
}
439
440
10176
void NodePlatform::DrainTasks(Isolate* isolate) {
441
10176
  std::shared_ptr<PerIsolatePlatformData> per_isolate = ForNodeIsolate(isolate);
442
10176
  if (!per_isolate) return;
443
444
4083
  do {
445
    // Worker tasks aren't associated with an Isolate.
446
14258
    worker_thread_task_runner_->BlockingDrain();
447
14258
  } while (per_isolate->FlushForegroundTasksInternal());
448
}
449
450
22234
bool PerIsolatePlatformData::FlushForegroundTasksInternal() {
451
22234
  bool did_work = false;
452
453
  while (std::unique_ptr<DelayedTask> delayed =
454
27192
      foreground_delayed_tasks_.Pop()) {
455
4958
    did_work = true;
456
4958
    uint64_t delay_millis = llround(delayed->timeout * 1000);
457
458
4958
    delayed->timer.data = static_cast<void*>(delayed.get());
459
4958
    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
4958
    uv_timer_start(&delayed->timer, RunForegroundTask, delay_millis, 0);
463
4958
    uv_unref(reinterpret_cast<uv_handle_t*>(&delayed->timer));
464
4958
    uv_handle_count_++;
465
466
14874
    scheduled_delayed_tasks_.emplace_back(delayed.release(),
467
4800
                                          [](DelayedTask* delayed) {
468
4800
      uv_close(reinterpret_cast<uv_handle_t*>(&delayed->timer),
469
623
               [](uv_handle_t* handle) {
470
        std::unique_ptr<DelayedTask> task {
471
1246
            static_cast<DelayedTask*>(handle->data) };
472
623
        task->platform_data->DecreaseHandleCount();
473
623
      });
474
4958
    });
475
4958
  }
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
22234
  std::queue<std::unique_ptr<Task>> tasks = foreground_tasks_.PopAll();
480
31200
  while (!tasks.empty()) {
481
8973
    std::unique_ptr<Task> task = std::move(tasks.front());
482
8973
    tasks.pop();
483
8973
    did_work = true;
484
8973
    RunForegroundTask(std::move(task));
485
  }
486
22227
  return did_work;
487
}
488
489
96205
void NodePlatform::CallOnWorkerThread(std::unique_ptr<Task> task) {
490
96205
  worker_thread_task_runner_->PostTask(std::move(task));
491
96205
}
492
493
527
void NodePlatform::CallDelayedOnWorkerThread(std::unique_ptr<Task> task,
494
                                             double delay_in_seconds) {
495
527
  worker_thread_task_runner_->PostDelayedTask(std::move(task),
496
                                              delay_in_seconds);
497
527
}
498
499
500
26133
IsolatePlatformDelegate* NodePlatform::ForIsolate(Isolate* isolate) {
501
52266
  Mutex::ScopedLock lock(per_isolate_mutex_);
502
26133
  auto data = per_isolate_[isolate];
503
26133
  CHECK_NOT_NULL(data.first);
504
26133
  return data.first;
505
}
506
507
std::shared_ptr<PerIsolatePlatformData>
508
10180
NodePlatform::ForNodeIsolate(Isolate* isolate) {
509
20360
  Mutex::ScopedLock lock(per_isolate_mutex_);
510
20360
  auto data = per_isolate_[isolate];
511
10180
  CHECK_NOT_NULL(data.first);
512
10180
  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
26345
std::unique_ptr<v8::JobHandle> NodePlatform::PostJob(v8::TaskPriority priority,
522
                                       std::unique_ptr<v8::JobTask> job_task) {
523
  return v8::platform::NewDefaultJobHandle(
524
26345
      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
26133
NodePlatform::GetForegroundTaskRunner(Isolate* isolate) {
533
26133
  return ForIsolate(isolate)->GetForegroundTaskRunner();
534
}
535
536
205835
double NodePlatform::MonotonicallyIncreasingTime() {
537
  // Convert nanos to seconds.
538
205835
  return uv_hrtime() / 1e9;
539
}
540
541
16075578
double NodePlatform::CurrentClockTimeMillis() {
542
16075578
  return SystemClockTimeMillis();
543
}
544
545
294653
v8::TracingController* NodePlatform::GetTracingController() {
546
294653
  CHECK_NOT_NULL(tracing_controller_);
547
294653
  return tracing_controller_;
548
}
549
550
5019
Platform::StackTracePrinter NodePlatform::GetStackTracePrinter() {
551
  return []() {
552
    fprintf(stderr, "\n");
553
    DumpBacktrace(stderr);
554
    fflush(stderr);
555
5019
  };
556
}
557
558
5020
v8::PageAllocator* NodePlatform::GetPageAllocator() {
559
5020
  return page_allocator_;
560
}
561
562
template <class T>
563
42728
TaskQueue<T>::TaskQueue()
564
    : lock_(), tasks_available_(), tasks_drained_(),
565
42728
      outstanding_tasks_(0), stopped_(false), task_queue_() { }
566
567
template <class T>
568
232886
void TaskQueue<T>::Push(std::unique_ptr<T> task) {
569
465772
  Mutex::ScopedLock scoped_lock(lock_);
570
232886
  outstanding_tasks_++;
571
232886
  task_queue_.push(std::move(task));
572
232886
  tasks_available_.Signal(scoped_lock);
573
232886
}
574
575
template <class T>
576
76540
std::unique_ptr<T> TaskQueue<T>::Pop() {
577
153080
  Mutex::ScopedLock scoped_lock(lock_);
578
76540
  if (task_queue_.empty()) {
579
55546
    return std::unique_ptr<T>(nullptr);
580
  }
581
41988
  std::unique_ptr<T> result = std::move(task_queue_.front());
582
20994
  task_queue_.pop();
583
20994
  return result;
584
}
585
586
template <class T>
587
116455
std::unique_ptr<T> TaskQueue<T>::BlockingPop() {
588
232882
  Mutex::ScopedLock scoped_lock(lock_);
589

224045
  while (task_queue_.empty() && !stopped_) {
590
107618
    tasks_available_.Wait(scoped_lock);
591
  }
592
116427
  if (stopped_) {
593
20054
    return std::unique_ptr<T>(nullptr);
594
  }
595
192746
  std::unique_ptr<T> result = std::move(task_queue_.front());
596
96373
  task_queue_.pop();
597
96373
  return result;
598
}
599
600
template <class T>
601
96373
void TaskQueue<T>::NotifyOfCompletion() {
602
192746
  Mutex::ScopedLock scoped_lock(lock_);
603
96373
  if (--outstanding_tasks_ == 0) {
604
40325
    tasks_drained_.Broadcast(scoped_lock);
605
  }
606
96373
}
607
608
template <class T>
609
14258
void TaskQueue<T>::BlockingDrain() {
610
28516
  Mutex::ScopedLock scoped_lock(lock_);
611
15554
  while (outstanding_tasks_ > 0) {
612
1296
    tasks_drained_.Wait(scoped_lock);
613
  }
614
14258
}
615
616
template <class T>
617
5012
void TaskQueue<T>::Stop() {
618
10024
  Mutex::ScopedLock scoped_lock(lock_);
619
5012
  stopped_ = true;
620
5012
  tasks_available_.Broadcast(scoped_lock);
621
5012
}
622
623
template <class T>
624
32564
std::queue<std::unique_ptr<T>> TaskQueue<T>::PopAll() {
625
65128
  Mutex::ScopedLock scoped_lock(lock_);
626
32564
  std::queue<std::unique_ptr<T>> result;
627
32564
  result.swap(task_queue_);
628
32564
  return result;
629
}
630
631
}  // namespace node