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 #ifndef V8_LIBPLATFORM_DEFAULT_WORKER_THREADS_TASK_RUNNER_H_ 6 #define V8_LIBPLATFORM_DEFAULT_WORKER_THREADS_TASK_RUNNER_H_ 7 8 #include <memory> 9 #include <vector> 10 11 #include "include/libplatform/libplatform-export.h" 12 #include "include/v8-platform.h" 13 #include "src/base/platform/mutex.h" 14 #include "src/base/platform/platform.h" 15 #include "src/libplatform/delayed-task-queue.h" 16 17 namespace v8 { 18 namespace platform { 19 20 class V8_PLATFORM_EXPORT DefaultWorkerThreadsTaskRunner NON_EXPORTED_BASE(TaskRunner)21 : public NON_EXPORTED_BASE(TaskRunner) { 22 public: 23 using TimeFunction = double (*)(); 24 25 DefaultWorkerThreadsTaskRunner(uint32_t thread_pool_size, 26 TimeFunction time_function); 27 28 ~DefaultWorkerThreadsTaskRunner() override; 29 30 void Terminate(); 31 32 double MonotonicallyIncreasingTime(); 33 34 // v8::TaskRunner implementation. 35 void PostTask(std::unique_ptr<Task> task) override; 36 37 void PostDelayedTask(std::unique_ptr<Task> task, 38 double delay_in_seconds) override; 39 40 void PostIdleTask(std::unique_ptr<IdleTask> task) override; 41 42 bool IdleTasksEnabled() override; 43 44 private: 45 class WorkerThread : public base::Thread { 46 public: 47 explicit WorkerThread(DefaultWorkerThreadsTaskRunner* runner); 48 ~WorkerThread() override; 49 50 WorkerThread(const WorkerThread&) = delete; 51 WorkerThread& operator=(const WorkerThread&) = delete; 52 53 // This thread attempts to get tasks in a loop from |runner_| and run them. 54 void Run() override; 55 56 private: 57 DefaultWorkerThreadsTaskRunner* runner_; 58 }; 59 60 // Called by the WorkerThread. Gets the next take (delayed or immediate) to be 61 // executed. Blocks if no task is available. 62 std::unique_ptr<Task> GetNext(); 63 64 bool terminated_ = false; 65 base::Mutex lock_; 66 DelayedTaskQueue queue_; 67 std::vector<std::unique_ptr<WorkerThread>> thread_pool_; 68 TimeFunction time_function_; 69 }; 70 71 } // namespace platform 72 } // namespace v8 73 74 #endif // V8_LIBPLATFORM_DEFAULT_WORKER_THREADS_TASK_RUNNER_H_ 75