1 // Copyright 2013 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.
5 #include "src/libplatform/default-platform.h"
10 #include "src/base/logging.h"
11 #include "src/base/platform/platform.h"
12 #include "src/libplatform/worker-thread.h"
18 v8::Platform* CreateDefaultPlatform(int thread_pool_size) {
19 DefaultPlatform* platform = new DefaultPlatform();
20 platform->SetThreadPoolSize(thread_pool_size);
21 platform->EnsureInitialized();
26 bool PumpMessageLoop(v8::Platform* platform, v8::Isolate* isolate) {
27 return reinterpret_cast<DefaultPlatform*>(platform)->PumpMessageLoop(isolate);
31 const int DefaultPlatform::kMaxThreadPoolSize = 4;
34 DefaultPlatform::DefaultPlatform()
35 : initialized_(false), thread_pool_size_(0) {}
38 DefaultPlatform::~DefaultPlatform() {
39 base::LockGuard<base::Mutex> guard(&lock_);
42 for (std::vector<WorkerThread*>::iterator i = thread_pool_.begin();
43 i != thread_pool_.end(); ++i) {
47 for (std::map<v8::Isolate*, std::queue<Task*> >::iterator i =
48 main_thread_queue_.begin();
49 i != main_thread_queue_.end(); ++i) {
50 while (!i->second.empty()) {
51 delete i->second.front();
58 void DefaultPlatform::SetThreadPoolSize(int thread_pool_size) {
59 base::LockGuard<base::Mutex> guard(&lock_);
60 DCHECK(thread_pool_size >= 0);
61 if (thread_pool_size < 1)
62 thread_pool_size = base::OS::NumberOfProcessorsOnline();
64 std::max(std::min(thread_pool_size, kMaxThreadPoolSize), 1);
68 void DefaultPlatform::EnsureInitialized() {
69 base::LockGuard<base::Mutex> guard(&lock_);
70 if (initialized_) return;
73 for (int i = 0; i < thread_pool_size_; ++i)
74 thread_pool_.push_back(new WorkerThread(&queue_));
78 bool DefaultPlatform::PumpMessageLoop(v8::Isolate* isolate) {
81 base::LockGuard<base::Mutex> guard(&lock_);
82 std::map<v8::Isolate*, std::queue<Task*> >::iterator it =
83 main_thread_queue_.find(isolate);
84 if (it == main_thread_queue_.end() || it->second.empty()) {
87 task = it->second.front();
95 void DefaultPlatform::CallOnBackgroundThread(Task *task,
96 ExpectedRuntime expected_runtime) {
102 void DefaultPlatform::CallOnForegroundThread(v8::Isolate* isolate, Task* task) {
103 base::LockGuard<base::Mutex> guard(&lock_);
104 main_thread_queue_[isolate].push(task);
107 } } // namespace v8::platform