当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 浅析libuv源码-node事件轮询解析(2)

浅析libuv源码-node事件轮询解析(2)

2019年05月08日  | 移动技术网IT编程  | 我要评论
上一篇讲了轮询的边角料,这篇进入正题。 Poll for I/O The loop blocks for I/O. At this point the loop will block for I/O for the duration calculated in the previous step. ...

  上一篇讲了轮询的边角料,这篇进入正题。

 

poll for i/o

  the loop blocks for i/o. at this point the loop will block for i/o for the duration calculated in the previous step. all i/o related handles that were monitoring a given file descriptor for a read or write operation get their callbacks called at this point.

  简单来讲,就两点:

1、根据计算的timeout来进行i/o操作,这里的操作包括fs.readfile、fs.stat等,期间进程将被阻塞。

2、所有i/o的handles会使用一个给定的文件描述符进行操作,并会调用对应的callbacks。

 

call pengding callbacks

  pending callbacks are called. all i/o callbacks are called right after polling for i/o, for the most part. there are cases, however, in which calling such a callback is deferred for the next loop iteration. if the previous iteration deferred any i/o callback it will be run at this point.

  从解释中看不出什么信息,但只有这一步真正调用我们从js传过去的callback。

 

  既然要解析,那么不如从一个api入手,走一遍看代码流向。

  这里还是用之前fs.stat方法,虽然在前面(https://www.cnblogs.com/qh-jimmy/p/9395985.html)有过看似很深入的解释,但也只是走马观花的看了一遍,这次重新梳理一遍。

  与上篇一样,省略大量无关源码。

 

javascript层

  同样从简易的lib/fs.js文件中出发,这次着重注意的是传过去的三个参数。

function stat(path, options, callback) {
  // ...
  // fsreqcallback是来源于c++层的一个class
  const req = new fsreqcallback(options.bigint);
  req.oncomplete = callback;
  // 这里的第三个参数是一个object 回调函数仅作为一个oncomplete属性
  binding.stat(pathmodule.tonamespacedpath(path), options.bigint, req);
}

  如下:

1、第一个是处理过的路径path

2、第二个是一个可选参数,一般情况没人传,本文也不会做解析,毕竟不是重点

3、第三个是一个新生成的对象,而不是将我们的function直接作为参数传到stat方法中

 

node层

  接下来直接到src/node_file.cc文件中,这里会检测参数并做包装,不用懂c++直接看注释。

static void stat(const functioncallbackinfo<value>& args) {
  environment* env = environment::getcurrent(args);
  // 检测参数数量是否大于2
  const int argc = args.length();
  check_ge(argc, 2);
  // 检测path参数合法性
  buffervalue path(env->isolate(), args[0]);
  check_not_null(*path);
  // 检测是否传了use_bigint
  bool use_bigint = args[1]->istrue();
  // 在同步调用stat的情况下 这个class为空指针
  // if、else后面有同步/异步调用时参数情况
  fsreqbase* req_wrap_async = getreqwrap(env, args[2], use_bigint);
  if (req_wrap_async != nullptr) {  // stat(path, use_bigint, req)
    asynccall(env, req_wrap_async, args, "stat", utf8, afterstat,
              uv_fs_stat, *path);
  } else {  // stat(path, use_bigint, undefined, ctx)
    // 同步情况...
  }
}

  在之前那一篇讲node架构时,这块只是简单说了一下,直接跳到同步调用那块了。

  但是只有在异步调用的时候才会出现poll for i/o,所以这次跳过同步情况,来看异步调用情况。(那一篇的异步情况是瞎鸡儿乱说的,根本没法看)

  首先整理一下asynccall方法的参数。

asynccall(env, req_wrap_async, args, "stat", utf8, afterstat,uv_fs_stat, *path);

env => 一个万能的全局对象,能存东西能做事情。可以通过env->isolate获当前取v8引擎实例,env->setmethod设置js的对象属性等等

req_wrap_async => 一个包装类

args => 从javascript层传过来的函数数组,可以简单理解为arguments

"stat" => 需要调用的fs方法名字符串

utf8 => 编码类型

afterstat => 一个内置的一个回调函数

uv_fs_stat => 异步调用的实际方法

*path => 路径参数

  参数看完,可以进到方法里,这是一个模版函数,不过也没啥。

// func类型为普通函数
// args为路径path
template <typename func, typename... args>
inline fsreqbase* asynccall(environment* env,
    fsreqbase* req_wrap,
    const functioncallbackinfo<value>& args,
    const char* syscall, enum encoding enc,
    uv_fs_cb after, func fn, args... fn_args) {
  return asyncdestcall(env, req_wrap, args, syscall, nullptr, 0, enc, after, fn, fn_args...);
}

template <typename func, typename... args>
inline fsreqbase* asyncdestcall(environment* env,
    fsreqbase* req_wrap,
    const functioncallbackinfo<value>& args,
    const char* syscall, const char* dest, size_t len,
    enum encoding enc, uv_fs_cb after, func fn, args... fn_args) {
  // 异步调用这个类不能为空指针
  check_not_null(req_wrap);
  // 依次调用包装类的方法
  req_wrap->init(syscall, dest, len, enc);
  int err = req_wrap->dispatch(fn, fn_args..., after);
  if (err < 0) {
    // 出现error的情况 不用看...
  } else {
    req_wrap->setreturnvalue(args);
  }

  return req_wrap;
}

  看似一大团,实际上函数内容非常少,仅仅只有一个init、一个dispatch便完成了整个stat操作。

  由于都来源于req_wrap类,所以需要回头去看一下这个类的内容。

fsreqbase* req_wrap_async = getreqwrap(env, args[2], use_bigint);
inline fsreqbase* getreqwrap(environment* env, local<value> value, bool use_bigint = false) {
  if (value->isobject()) {
    return unwrap<fsreqbase>(value.as<object>());
  } else if (value->strictequals(env->fs_use_promises_symbol())) {
    // promise情况...
  }
  return nullptr;
}

  不用看promise的情况,在最开始的讲过,传过来的第三个参数是一个新生成的对象,所以这里的args[2]正好满足value->isobject()。

  这里的return比较魔性,没有c++基础的不太好讲,先看看源码。

template <class t>
static inline t* unwrap(v8::local<v8::object> handle) {
  // ...
  // 这里是类型强转
  return static_cast<t*>(wrap);
}

class fsreqbase : public reqwrap<uv_fs_t> {
 public:
  // ...
  void init(const char* syscall, const char* data, size_t len, enum encoding encoding) {}
}

template <typename t>
class reqwrap : public asyncwrap, public reqwrapbase {
 public:
  // ...
  inline int dispatch(libuvfunction fn, args... args);

 private:
  // ...
};

  剔除了所有无关的代码,留下了一些关键信息。

  简单来讲,这里的unwrap是一个模版方法,作用仅仅是做一个强转,关键在于强转的fsreqbase类。这个类的继承链比较长,可以看出类本身有一个init,而在父类reqwrap上有dispatch方法,知道方法怎么来的,这就足够了。

  这里重新看那两步调用。

req_wrap->init(syscall, dest, len, enc);
int err = req_wrap->dispatch(fn, fn_args..., after);

  首先是init。

void init(const char* syscall, const char* data, size_t len, enum encoding encoding) {
  syscall_ = syscall;
  encoding_ = encoding;

  if (data != nullptr) {
    // ...
  }
}

  四个参数实际上分别是字符串"stat"、nullptr、0、枚举值uft8,所以这里的if不会走,只是两个赋值操作。

  接下来就是dispatch。

template <typename t>
template <typename libuvfunction, typename... args>
int reqwrap<t>::dispatch(libuvfunction fn, args... args) {
  dispatched();

  // this expands as:
  //
  // int err = fn(env()->event_loop(), req(), arg1, arg2, wrapper, arg3, ...)
  //              ^                                       ^        ^
  //              |                                       |        |
  //              \-- omitted if `fn` has no              |        |
  //                  first `uv_loop_t*` argument         |        |
  //                                                      |        |
  //        a function callback whose first argument      |        |
  //        matches the libuv request type is replaced ---/        |
  //        by the `wrapper` method defined above                  |
  //                                                               |
  //               other (non-function) arguments are passed  -----/
  //               through verbatim
  int err = calllibuvfunction<t, libuvfunction>::call(fn, env()->event_loop(), req(), makelibuvrequestcallback<t, args>::for(this, args)...);
  if (err >= 0)
    env()->increasewaitingrequestcounter();
  return err;
}

  这个方法的内容展开之后巨麻烦,懒得讲了,直接看官方给的注释。

  简单来说,就是相当于直接调用给的uv_fs_stat,参数依次为事件轮询的全局对象loop、fs专用handle、路径path、包装的callback函数。

  这篇先这样。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网