上一篇分析了prepare阶段,check和idle阶段是一样的,所以就不分析了。今天分析定时器阶段。nodejs中setTimeout和setInterval就是使用libuv的定时器阶段实现的。libuv中,定时器是以最小堆实现的。即最快过期的节点是根节点。我看看定时器的数据结构。
看一下定时器的使用。
int main()
v_timer_t once;
uv_timer_init(uv_default_loop(), &once);
uv_timer_start(&once, once_cb, 10, 0);
uv_run(uv_default_loop(), UV_RUN_DEFAULT);
return 0;
}
我们从uv_timer_init函数开始分析。
// 初始化uv_timer_t结构体
int uv_timer_init(uv_loop_t* loop, uv_timer_t* handle) {
uv__handle_init(loop, (uv_handle_t*)handle, UV_TIMER);
handle->timer_cb = NULL;
handle->repeat = 0;
return 0;
}
init函数和其他阶段的init函数一样,初始化handle和私有的一些字段。接着我们看start函数。该函数是启动一个定时器(省略部分代码)。
// 启动一个计时器
int uv_timer_start(
uv_timer_t* handle,
uv_timer_cb cb,
uint64_t timeout,
uint64_t repeat
) {
uint64_t clamped_timeout;
// 重新执行start的时候先把之前的停掉
if (uv__is_active(handle))
uv_timer_stop(handle);
// 超时时间,为绝对值
clamped_timeout = handle->loop->time + timeout;
// 初始化回调,超时时间,是否重复计时,赋予一个独立无二的id
handle->timer_cb = cb;
handle->timeout = clamped_timeout;
handle->repeat = repeat;
/* start_id is the second index to be compared in uv__timer_cmp() */
handle->start_id = handle->loop->timer_counter++;
// 插入最小堆
heap_insert(timer_heap(handle->loop),
(struct heap_node*) &handle->heap_node,
timer_less_than);
// 激活该handle
uv__handle_start(handle);
return 0;
}
start函数首先初始化handle里的某些字段,包括超时回调,是否重复启动定时器、超时的绝对时间等。接着把handle节点插入到最小堆中。最后给这个handle打上标记,激活这个handle。这时候的结构体如下。
这时候到了事件循环的timer阶段。
// 找出已经超时的节点,并且执行里面的回调
void uv__run_timers(uv_loop_t* loop) {
struct heap_node* heap_node;
uv_timer_t* handle;
for (;;) {
heap_node = heap_min(timer_heap(loop));
if (heap_node == NULL)
break;
handle = container_of(heap_node, uv_timer_t, heap_node);
// 如果当前节点的时间大于当前时间则返回,说明后面的节点也没有超时
if (handle->timeout > loop->time)
break;
// 移除该计时器节点,重新插入最小堆,如果设置了repeat的话
uv_timer_stop(handle);
uv_timer_again(handle);
// 执行超时回调
handle->timer_cb(handle);
}
}
libuv在每次事件循环开始的时候都会缓存当前的时间,在整个一轮的事件循环中,使用的都是这个缓存的时间。缓存了当前最新的时间后,就执行uv__run_timers,该函数的逻辑很明了,就是遍历最小堆,找出当前超时的节点。因为堆的性质是父节点肯定比孩子小。所以如果找到一个节点,他没有超时,则后面的节点也不会超时。对于超时的节点就知道他的回调。执行完回调后,还有两个关键的操作。第一就是stop,第二就是again。
// 停止一个计时器
int