int uv_run(uv_loop_t *loop, uv_run_mode mode) {
// ...
while (r != 0 && loop->stop_flag == 0) {
// update loop time
uv_update_time(loop);
// run due timers
uv__run_timers(loop);
// call pending callbacks
ran_pending = uv_process_reqs(loop);
// run idle handles
uv_idle_invoke(loop);
// run prepare handles
uv_prepare_invoke(loop);
// poll的阻塞時間處理
timeout = 0;
if ((mode == UV_RUN_ONCE && !ran_pending) || mode == UV_RUN_DEFAULT)
timeout = uv_backend_timeout(loop);
// poll for I/O
if (pGetQueuedCompletionStatusEx)
uv__poll(loop, timeout);
else
uv__poll_wine(loop, timeout);
// run check handles
uv_check_invoke(loop);
// call close callbacks
uv_process_endgames(loop);
}
// ...
return r;
}複製代碼
Call close callbackshtml
void uv_close(uv_handle_t* handle, uv_close_cb cb) {
// 不少代碼...
case UV_PREPARE:
uv_prepare_stop((uv_prepare_t*)handle);
uv__handle_closing(handle);
uv_want_endgame(loop, handle);
return;
}複製代碼
INLINE static void uv_want_endgame(uv_loop_t* loop, uv_handle_t* handle) {
if (!(handle->flags & UV_HANDLE_ENDGAME_QUEUED)) {
handle->flags |= UV_HANDLE_ENDGAME_QUEUED;
handle->endgame_next = loop->endgame_handles;
loop->endgame_handles = handle;
}
}複製代碼
INLINE static void uv_process_endgames(uv_loop_t* loop) {
uv_handle_t* handle;
while (loop->endgame_handles) {
handle = loop->endgame_handles;
loop->endgame_handles = handle->endgame_next;
handle->flags &= ~UV_HANDLE_ENDGAME_QUEUED;
switch (handle->type) {
case UV_TCP:
uv_tcp_endgame(loop, (uv_tcp_t*) handle);
break;
// ...
}
}
}複製代碼
#include <iostream>
#include "uv.h"
using namespace std;
void idle_callback(uv_idle_t* idle);
void prepare_callback(uv_prepare_t* prepare);
void check_callback(uv_check_t* check);
#define RUN_HANDLE(type) \ do { \ uv_##type##_t type; \ uv_##type##_init(loop, &type); \ uv_##type##_start(&type, type##_callback); \ } while(0)
#define CALLBACK(type) \ do { \ cout << "Run " << #type << " handles" << endl; \ uv_##type##_stop(type); \ } while(0)
#define OPEN(PATH, callback) \ do { \ uv_fs_t req; \ uv_fs_open(loop, &req, PATH, O_RDONLY, 0, callback); \ uv_fs_req_cleanup(&req); \ } while(0)
void idle_callback(uv_idle_t* idle) { CALLBACK(idle); }
void prepare_callback(uv_prepare_t* prepare) { CALLBACK(prepare); }
void check_callback(uv_check_t* check) { CALLBACK(check); }
void on_open(uv_fs_t* req) { cout << "poll for I/O" << endl; }
int main(int argc, const char * argv[]) {
auto loop = uv_default_loop();
RUN_HANDLE(check);
RUN_HANDLE(prepare);
RUN_HANDLE(idle);
OPEN("/Users/feilongpang/workspace/i.js", on_open);
uv_run(loop, UV_RUN_DEFAULT);
uv_loop_close(loop);
return 0;
}複製代碼