本教程介绍 libcc 的事件模型与时间轮计时器,包含示例:创建事件管理器、添加定时器与处理回调。
#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;
}
async.running = true;
/* 添加 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;
}
与其他示例相同:使用仓库的 `Makefile` 或通过手动编译并链接生成的 libcc 库。
make .bin target=tests build=event