1// Copyright 2017 the V8 project authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5#include "src/libplatform/default-worker-threads-task-runner.h" 6 7#include "src/libplatform/delayed-task-queue.h" 8 9namespace v8 { 10namespace platform { 11 12DefaultWorkerThreadsTaskRunner::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 20DefaultWorkerThreadsTaskRunner::~DefaultWorkerThreadsTaskRunner() = default; 21 22double DefaultWorkerThreadsTaskRunner::MonotonicallyIncreasingTime() { 23 return time_function_(); 24} 25 26void DefaultWorkerThreadsTaskRunner::Terminate() { 27 base::MutexGuard guard(&lock_); 28 terminated_ = true; 29 queue_.Terminate(); 30 // Clearing the thread pool lets all worker threads join. 31 thread_pool_.clear(); 32} 33 34void DefaultWorkerThreadsTaskRunner::PostTask(std::unique_ptr<Task> task) { 35 base::MutexGuard guard(&lock_); 36 if (terminated_) return; 37 queue_.Append(std::move(task)); 38} 39 40void DefaultWorkerThreadsTaskRunner::PostDelayedTask(std::unique_ptr<Task> task, 41 double delay_in_seconds) { 42 base::MutexGuard guard(&lock_); 43 if (terminated_) return; 44 queue_.AppendDelayed(std::move(task), delay_in_seconds); 45} 46 47void DefaultWorkerThreadsTaskRunner::PostIdleTask( 48 std::unique_ptr<IdleTask> task) { 49 // There are no idle worker tasks. 50 UNREACHABLE(); 51} 52 53bool DefaultWorkerThreadsTaskRunner::IdleTasksEnabled() { 54 // There are no idle worker tasks. 55 return false; 56} 57 58std::unique_ptr<Task> DefaultWorkerThreadsTaskRunner::GetNext() { 59 return queue_.GetNext(); 60} 61 62DefaultWorkerThreadsTaskRunner::WorkerThread::WorkerThread( 63 DefaultWorkerThreadsTaskRunner* runner) 64 : Thread(Options("V8 DefaultWorkerThreadsTaskRunner WorkerThread")), 65 runner_(runner) { 66 CHECK(Start()); 67} 68 69DefaultWorkerThreadsTaskRunner::WorkerThread::~WorkerThread() { Join(); } 70 71void DefaultWorkerThreadsTaskRunner::WorkerThread::Run() { 72 while (std::unique_ptr<Task> task = runner_->GetNext()) { 73 task->Run(); 74 } 75} 76 77} // namespace platform 78} // namespace v8 79