1. 程式人生 > >淺析libuv原始碼-node事件輪詢解析(2)

淺析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.

  簡單來講,就兩點:

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函式。

  這篇先這