default-worker-threads-task-runner.cc 2.27 KB
Newer Older
1 2 3 4
// Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
#include "src/libplatform/default-worker-threads-task-runner.h"
6

7
#include "src/libplatform/delayed-task-queue.h"
8 9 10 11

namespace v8 {
namespace platform {

12
DefaultWorkerThreadsTaskRunner::DefaultWorkerThreadsTaskRunner(
13
    uint32_t thread_pool_size, TimeFunction time_function)
14
    : queue_(time_function), time_function_(time_function) {
15
  for (uint32_t i = 0; i < thread_pool_size; ++i) {
16
    thread_pool_.push_back(std::make_unique<WorkerThread>(this));
17 18 19
  }
}

20 21 22 23
DefaultWorkerThreadsTaskRunner::~DefaultWorkerThreadsTaskRunner() = default;

double DefaultWorkerThreadsTaskRunner::MonotonicallyIncreasingTime() {
  return time_function_();
24 25
}

26
void DefaultWorkerThreadsTaskRunner::Terminate() {
27
  base::MutexGuard guard(&lock_);
28
  terminated_ = true;
29 30 31
  queue_.Terminate();
  // Clearing the thread pool lets all worker threads join.
  thread_pool_.clear();
32 33
}

34
void DefaultWorkerThreadsTaskRunner::PostTask(std::unique_ptr<Task> task) {
35
  base::MutexGuard guard(&lock_);
36 37 38 39
  if (terminated_) return;
  queue_.Append(std::move(task));
}

40 41
void DefaultWorkerThreadsTaskRunner::PostDelayedTask(std::unique_ptr<Task> task,
                                                     double delay_in_seconds) {
42
  base::MutexGuard guard(&lock_);
43
  if (terminated_) return;
44
  queue_.AppendDelayed(std::move(task), delay_in_seconds);
45 46
}

47 48 49
void DefaultWorkerThreadsTaskRunner::PostIdleTask(
    std::unique_ptr<IdleTask> task) {
  // There are no idle worker tasks.
50 51 52
  UNREACHABLE();
}

53 54
bool DefaultWorkerThreadsTaskRunner::IdleTasksEnabled() {
  // There are no idle worker tasks.
55 56 57
  return false;
}

58 59 60 61 62 63 64 65
std::unique_ptr<Task> DefaultWorkerThreadsTaskRunner::GetNext() {
  return queue_.GetNext();
}

DefaultWorkerThreadsTaskRunner::WorkerThread::WorkerThread(
    DefaultWorkerThreadsTaskRunner* runner)
    : Thread(Options("V8 DefaultWorkerThreadsTaskRunner WorkerThread")),
      runner_(runner) {
66
  CHECK(Start());
67 68 69 70 71 72 73 74 75 76
}

DefaultWorkerThreadsTaskRunner::WorkerThread::~WorkerThread() { Join(); }

void DefaultWorkerThreadsTaskRunner::WorkerThread::Run() {
  while (std::unique_ptr<Task> task = runner_->GetNext()) {
    task->Run();
  }
}

77 78
}  // namespace platform
}  // namespace v8