事件循环与定时器
本教程介绍 libcc 的事件模型与时间轮计时器,包含示例:创建事件管理器、添加定时器与处理回调。
核心概念
_cc_async_event_t:事件管理器,封装平台轮询(epoll/kqueue/iocp 等),管理事件列表与时间轮。_cc_event_t:具体事件(socket、定时器、文件等),包含 flags、回调与超时时间。
时间轮:高效的软定时器实现,使用 _cc_add_event_timeout/_cc_kill_event_timeout 等 API。
示例代码(tests/event.c)
#include <stdio.h>
#include <libcc.h>
static bool_t timer_cb(_cc_async_event_t *async, _cc_event_t *e, const uint32_t which) {
if (which & _CC_EVENT_TIMEOUT_) {
_cc_logger_info(_T("[event-loop] timeout ident=%d data=%ld"), e->ident, e->data);
/* 停止事件循环 */
async->running = false;
return false;
}
return true;
}
int main(void) {
_cc_async_event_t async;
_cc_event_t *ev;
/* 在平台上注册 poller(macOS 使用 kqueue) */
if (!_cc_register_kqueue(&async)) {
fprintf(stderr, "register kqueue failed\n");
return -1;
}
/* 添加 2 秒定时器 */
ev = _cc_add_event_timeout(&async, 2000, timer_cb, 42);
if (!ev) return -1;
/* 事件循环 */
while (async.running) {
async.wait(&async, 500);
}
async.free(&async);
return 0;
}