Timer handles are used to schedule callbacks to be called in the future.
libuv的Timer模塊的實現(xiàn)還是相對簡單的痊臭,對libuv的解析就從Timer模塊開始。
數(shù)據(jù)結(jié)構(gòu)
Timer模塊的Handle Type(這里可以理解為Timer實例的數(shù)據(jù)結(jié)構(gòu))是uv_timer_s狸窘,其內(nèi)容如下:
struct uv_timer_s {
UV_HANDLE_FIELDS
UV_TIMER_PRIVATE_FIELDS
};
#define UV_TIMER_PRIVATE_FIELDS
uv_timer_cb timer_cb; #timer到期時的回調(diào)函數(shù)
void* heap_node[3]; #用于維護(hù)timer的最小堆
uint64_t timeout; #timer的超時時間袁辈,其實是到多長時間后timer被觸發(fā)
uint64_t repeat; #timer是否重復(fù)
uint64_t start_id;
接口
1. uv_timer_init
uv_timer_init接口的實現(xiàn)很簡單。
# file: timer.c
int uv_timer_init(uv_loop_t* loop, uv_timer_t* handle) {
uv__handle_init(loop, (uv_handle_t*)handle, UV_TIMER); [1]
handle->timer_cb = NULL;
handle->repeat = 0;
return 0;
}
代碼[1]對uv_handle_t進(jìn)行了初始化隙弛。來看一下uv__handle_init宏定義。
#define uv__handle_init(loop_, h, type_)
do {
(h)->loop = (loop_);
(h)->type = (type_);
(h)->flags = UV__HANDLE_REF;
QUEUE_INSERT_TAIL(&(loop_)->handle_queue, &(h)->handle_queue); [1]
uv__handle_platform_init(h);
}
while (0)
其中最關(guān)鍵的部分是將h(uv_handle_t)加入loop->handle_queue的隊列中去。
2. uv_timer_start
uv_timer_start接口的主要任務(wù)就是將uv_timer_t這個handler加入loop維護(hù)的一個最小堆中(timer_heap)
int uv_timer_start(uv_timer_t* handle,
uv_timer_cb cb,
uint64_t timeout,
uint64_t repeat) {
uint64_t clamped_timeout;
if (cb == NULL)
return -EINVAL;
if (uv__is_active(handle))
uv_timer_stop(handle);
......
heap_insert((struct heap*) &handle->loop->timer_heap,
(struct heap_node*) &handle->heap_node,
timer_less_than);
uv__handle_start(handle);
return 0;
}
3.uv_timer_stop
uv_timer_stop做的事情更簡單了叁征,他將Timer中timer_heap中刪除掉并關(guān)閉handler。
小結(jié)
libuv里面Timer是非常簡單的模塊了逛薇,