aultWorkerThreadsTaskRunner : public TaskRunner {
public:
using TimeFunction = double (*)();
DefaultWorkerThreadsTaskRunner(uint32_t thread_pool_size, TimeFunction time_function);
private:
class WorkerThread : public Thread {
public:
explicit WorkerThread(DefaultWorkerThreadsTaskRunner* runner);
~WorkerThread() override;
// This thread attempts to get tasks in a loop from |runner_| and run them.
void Run() override;
private:
DefaultWorkerThreadsTaskRunner* runner_;
};
// 获取下一个task
std::unique_ptr<Task> GetNext();
bool terminated_ = false;
// task队列
DelayedTaskQueue queue_;
// 线程池
std::vector<std::unique_ptr<WorkerThread>> thread_pool_;
// 计数方法
TimeFunction time_function_;
std::atomic_int single_worker_thread_id_{0};
uint32_t thread_pool_size_;
};
这里顺便把TaskRunner相关的内容也一并放出来,大部分内容可以看命名。内部类的初始化参数类型是外部类,V8完全把Thread、TaskRunner两个类绑起来了。
Task
这个只是一个简单基类,用来继承实现任务的。
/**
* A Task represents a unit of work.
*/
class Task {
public:
virtual ~Task() = default;
// 所有的task需要继承这个类并实现Run方法
virtual void Run() = 0;
};
由于HelloWorld的sample并没有用到多线程,所以不存在Task类的实现,这里只能先关注概念。使用时,大概方法如下,写个伪代码演示下。
class userTask : public Task {
public:
void Run() {
// do something...
};
};
void handleTask() {
// 新建一个task
auto task = new userTask();
// 加入队列
queue_.push_back(task);
// 唤醒线程
thread_.signal();
// 线程处理task
while(true) {
if(queue_.empty()) break;
auto task = queue_pop_back();
task->Run();
}
// 线程等待唤醒
thread_.wait();
}
过程跟其实libuv的异步操作差不多,感觉编程的套路也就那样,看多了源码或者有实际开发经验的都熟悉。
这一篇就先介绍一些类(调用栈和内存管理先放着),了解后基本上V8中关于Platform的内容就差不多了。关于Thread、TaskRunner、Task三者的联系与运作,因为C++是速成的,没去了解这些东西的实际运用,所以暂时不在这里班门弄斧了。之前学Java的时候了解过线程,感觉无论是API的名字还是概念都差不多,有兴趣的可以自己去看看。