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

  上一篇讲了轮询的边角料,这篇进入正题。(补两个图)



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.
  简单来说,就两点:
一、根据计算的timeout来进行I/O操做,这里的操做包括fs.readFile、fs.stat等,期间进程将被阻塞。
二、全部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方法,虽然在前面( www.cnblogs.com/QH-Jimmy/p/…)有过看似很深刻的解释,但也只是蜻蜓点水的看了一遍,此次从新梳理一遍。
  与上篇同样,省略大量无关源码。

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);
}复制代码
  以下:
一、第一个是处理过的路径path
二、第二个是一个可选参数,通常状况没人传,本文也不会作解析,毕竟不是重点
三、第三个是一个新生成的对象,而不是将咱们的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++基础的不太好讲,先看看源码。
// 这个T表明须要被强转的类 即FsReqBase
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函数。
  这篇先这样。
相关文章
相关标签/搜索