本来寻思着写一篇"'Hello' + ', World'"是怎么从JS代码编译然后输出的,然而compile过程的复杂性远超我的想象,强上怕会走火入魔,还是老老实实先回家种田,找点咸鱼方法先写着。虽然说是咸鱼方法,但是V8任何一块拿出来都不简单,之前讲的Time模块说实话大概是属于源码里面幼儿园级别的,这次试试难一点的。

  V8的源码在本地编译完成后,会提供一个hello-world.cc的sample,里面有新手用户标准的初始化流程,如下。

int main(int argc, char* argv[]) {
// Initialize V8.
// 这个方法在mac不作为
v8::V8::InitializeICUDefaultLocation(argv[]);
// 读取指定名称的配置文件 也不用鸟
v8::V8::InitializeExternalStartupData(argv[]);
// 生成一个默认的platform对象
std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
// 初始化刚才的platform
v8::V8::InitializePlatform(platform.get());
// V8的初始化
v8::V8::Initialize(); // ...
}

  前两步不用去管,在入门阶段用不上。

  第三步是主要内容,探究生成的默认platform对象(当然也可以选择自己定制一个platform对象),这个类主要负责管理线程池、调用栈、事件队列等一些杂活。

  这一篇不会去深入方法一步一步走,里面内容太过于杂乱,跳来跳去的,先整体介绍一下所有涉及的类,有一个初步的印象(建议深入阅读所有基类的英文注释,解释的很明白)。

Platform

  首先当然是核心类Platform,但这是一个基类,里面的大部分方法都是虚函数。

/**
* V8 Platform abstraction layer.
*
* The embedder has to provide an implementation of this interface before
* initializing the rest of V8.
*/
class Platform {};

  如果需要定制platform来初始化V8,需要继承这个类并实现那些方法。一般情况下当然可以V8默认提供的类,即DefaultPlatform。

class DefaultPlatform : public Platform {
public:
// 接受一个枚举值、一个TracingController类的构造函数
explicit DefaultPlatform(
IdleTaskSupport idle_task_support = IdleTaskSupport::kDisabled,
std::unique_ptr<v8::TracingController> tracing_controller = {});
~DefaultPlatform() override;
// 设置线程池大小
void SetThreadPoolSize(int thread_pool_size);
// 初始化线程池、管理线程任务相关的方法
void EnsureBackgroundTaskRunnerInitialized();
private:
// 最大线程池数量 默认为8
static const int kMaxThreadPoolSize; int thread_pool_size_;
IdleTaskSupport idle_task_support_;
// 线程任务启动器
std::shared_ptr<DefaultWorkerThreadsTaskRunner> worker_threads_task_runner_;
// 工具类
std::unique_ptr<TracingController> tracing_controller_;
std::unique_ptr<PageAllocator> page_allocator_;
// 计数方法 用的是之前介绍的Time模块
TimeFunction time_function_for_testing_;
}; /**
* V8 Tracing controller.
*
* Can be implemented by an embedder to record trace events from V8.
*/
class TracingController {}; /**
* A V8 memory page allocator.
*
* Can be implemented by an embedder to manage large host OS allocations.
*/
class PageAllocator {};

  只选了一些初始化相关的方法,其实内容远比这个要多。其中还定义了两个类似于Platform的基类变量,一个负责调用栈追踪,一个负责内存管理。

TaskRunner/Thread

  接下来是任务执行者、线程,因为这两者基本上成对出现,所以放一起来看。

// Thread
//
// Thread objects are used for creating and running threads. When the start()
// method is called the new thread starts running the run() method in the new
// thread. The Thread object should not be deallocated before the thread has
// terminated. class V8_BASE_EXPORT Thread {
public:
// Start new thread by calling the Run() method on the new thread.
void Start();
// ...
};

  这是最基础的Thread,其中定义并实现了Start等常规方法,也有一些虚函数需要继承去重新实现,除此之外还有一些静态方法。默认情况下,V8实现了一个类继承于Thread,位置十分的隐蔽,在默认TaskRunner的private里面。

/**
* A TaskRunner allows scheduling of tasks. The TaskRunner may still be used to
* post tasks after the isolate gets destructed, but these tasks may not get
* executed anymore. All tasks posted to a given TaskRunner will be invoked in
* sequence. Tasks can be posted from any thread.
*/
class TaskRunner {}; class DefaultWorkerThreadsTaskRunner : 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_{};
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() = ;
};

  由于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的名字还是概念都差不多,有兴趣的可以自己去看看。

深入V8引擎-初始化默认Platform的更多相关文章

  1. 深入V8引擎-初始化之InitPlatform

    上一篇其实想讲初始化的第二步,但是内容比较无聊,所以换了一个话题,谈了谈v8的命名空间和宏,稍微轻松一下. 在这里还是接着说说初始化过程,毕竟写博客的初衷是对自己努力的记录,不是为了吸粉,这篇没图,对 ...

  2. 深入V8引擎-默认Platform之mac篇(2)

    先说结论,V8引擎在默认Platform中初始化的这个线程是用于处理类似于setTimeout的延时任务. 另外附一些图,包括继承树.关键属性归属.纯逻辑工作流程,对代码木得兴趣的看完图可以X掉了. ...

  3. 深入V8引擎-默认Platform之mac篇(1)

    又到了常规的堆砌代码凑文章字数环节,很多API我就直接贴官方的英文释义,个人翻译其实有时候并不是很准确,搞错了甚至会误导,还是尽量自己去理解. 首先看看入口方法. std::unique_ptr< ...

  4. 深入V8引擎-引擎内部类管理解析

    v8的初始化三部曲,前面花了三篇解决了第一步,由于只是生成了一个对象,第二步就是将其嵌入v8中,先看一下三个步骤. // 生成默认Platform对象 std::unique_ptr<v8::P ...

  5. 浅谈V8引擎中的垃圾回收机制

    最近在看<深入浅出nodejs>关于V8垃圾回收机制的章节,转自:http://blog.segmentfault.com/skyinlayer/1190000000440270 这篇文章 ...

  6. google v8引擎常见问题

    最近在项目中使用v8来进行扩展,下面简单说一下使用v8过程中遇到的一些问题.   v8的多线程调用 最初调研v8的测试代码是单线程的,后来一个项目在多线程中使用,出现了一些问题,后来看到参考3中的才恍 ...

  7. 一文搞懂V8引擎的垃圾回收

    引言 作为目前最流行的JavaScript引擎,V8引擎从出现的那一刻起便广泛受到人们的关注,我们知道,JavaScript可以高效地运行在浏览器和Nodejs这两大宿主环境中,也是因为背后有强大的V ...

  8. 探究JS V8引擎下的“数组”底层实现

    本文首发于 vivo互联网技术 微信公众号 链接:https://mp.weixin.qq.com/s/np9Yoo02pEv9n_LCusZn3Q作者:李超 JavaScript 中的数组有很多特性 ...

  9. 浅谈Chrome V8引擎中的垃圾回收机制

    垃圾回收器 JavaScript的垃圾回收器 JavaScript使用垃圾回收机制来自动管理内存.垃圾回收是一把双刃剑,其好处是可以大幅简化程序的内存管理代码,降低程序员的负担,减少因 长时间运转而带 ...

随机推荐

  1. APS系统生产流转方式和批量算法研究

    01.前言 在经济领域,生产型企业是经济的根基,有了生产型企业生产出的各种产品,才有物流.网上购物和金融融资等活动.对于生产型企业,其制造能力是其核心竞争力.如何提升制造能力一直是生产型企业面临的课题 ...

  2. 常用邮箱SMTP服务器地址大全

    常用邮箱SMTP服务器地址大全 阿里云邮箱(mail.aliyun.com) POP3服务器地址:pop3.aliyun.com(SSL加密端口:995:非加密端口:110) SMTP服务器地址:sm ...

  3. 【我的第一个现实漏洞分析】 CVE-2017-17215 华为智能路由器HG532 漏洞分析笔记

    0x00 基本信息 2017.11.27 Check Point团队报告华为 HG532 产品的远程命令执行漏洞(CVE-2017-17215),Mirai的升级版变种中已经使用该漏洞. 华为HG53 ...

  4. 11-numpy笔记-莫烦基础操作1

    代码 import numpy as np array = np.array([[1,2,5],[3,4,6]]) print('-1-') print('数组维度', array.ndim) pri ...

  5. JDOJ 1065 打倒苏联修正主义

    JDOJ 1065 https://neooj.com/oldoj/problem.php?id=1065 题目描述 [”客观”背景]苏修是苏联修正主义的简称.从1956年到1966年的10年间,过去 ...

  6. 你真的了解FastClick吗?

    你真的了解FastClick吗? 前段时间在做公司官网手机端菜单部分的时候,遇到一些很诡异的点击问题.比如菜单点击无效/双击才有效.在手指滑动的时候会触发点击事件.以及同样的事件处理在微信跟浏览器会有 ...

  7. [LeetCode] 914. X of a Kind in a Deck of Cards 一副牌中的X

    In a deck of cards, each card has an integer written on it. Return true if and only if you can choos ...

  8. [LeetCode] 223. Rectangle Area 矩形面积

    Find the total area covered by two rectilinearrectangles in a 2D plane. Each rectangle is defined by ...

  9. [LeetCode] 63. Unique Paths II 不同的路径之二

    A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The ...

  10. 仅逗oier们一笑(不定期更新中)(update.2019年12月8日)

    CCF的正确解释: //部分来自:朝阳的二愣子的CSDN博客.ydclyq 的博客 .拱垲的博客.Randolph's Blog. 编译下列程序,会有意想不到的惊喜哦(注意打开声音): #includ ...