libtask — 任务框架 API 参考
模块概述
libtask 是嵌入式装置的通用任务调度框架,包含三个子系统:
- 定时器:基于 timerfd + epoll 精确毫秒级定时
- 事件:基于位图 + pthread 条件变量的同步原语
- 消息队列:基于环形缓冲区的线程安全 FIFO
常量与类型
定时器标志
| 宏 |
值 |
说明 |
TASK_TIMER_FLAG_ONCE |
0x01 |
单次触发 |
TASK_TIMER_FLAG_PERIODIC |
0x02 |
周期触发 |
事件标志
| 宏 |
值 |
说明 |
TASK_EVENT_WAIT_FOREVER |
0xFFFFFFFF |
永久等待 |
TASK_EVENT_FLAG_AND |
0x01 |
AND 模式(所有位都置位) |
TASK_EVENT_FLAG_OR |
0x02 |
OR 模式(任意位置位) |
TASK_EVENT_FLAG_CLEAR |
0x04 |
接收后自动清除 |
回调类型
typedef void (*timer_func_cb)(void *arg);
不透明句柄
typedef void *stru_task_timer_t;
typedef void *stru_task_event_t;
typedef void *stru_task_msg_queue_t;
接口函数
通用延时
task_sleep_ms(ms)
毫秒级精度延时(内部使用 nanosleep)。
定时器
| 函数 |
说明 |
task_timer_create(name, cb, arg, timeout_ms, flags) |
创建定时器(不自动启动) |
task_timer_start(pt) |
启动 |
task_timer_stop(pt) |
停止 |
task_timer_restart(pt, timeout_ms) |
重启(可改周期) |
task_timer_destroy(pt) |
销毁 |
task_timer_is_active(pt) |
查询运行状态 |
事件
| 函数 |
说明 |
task_event_create(name) |
创建事件对象 |
task_event_destroy(pe) |
销毁 |
task_event_send(pe, bits) |
发送(置位+广播) |
task_event_recv(pe, set, opt, timeout_ms, recved) |
等待 |
task_event_clear(pe, bits) |
清除位 |
task_event_query(pe) |
查询当前位(非阻塞) |
消息队列
| 函数 |
说明 |
task_msg_queue_create(name, msg_size, msg_num) |
创建 |
task_msg_queue_destroy(pq) |
销毁 |
task_msg_queue_send(pq, msg, size) |
发送(阻塞) |
task_msg_queue_send_timeout(pq, msg, size, timeout_ms) |
发送(超时) |
task_msg_queue_recv(pq, msg, size, timeout_ms) |
接收(超时) |
task_msg_queue_try_recv(pq, msg, size) |
非阻塞接收 |
task_msg_queue_get_count(pq) |
获取消息数 |
task_msg_queue_space(pq) |
获取剩余空间 |
使用示例
定时器
#include "myTask.h"
#include <stdio.h>
static int tick_count = 0;
void on_tick(void *arg)
{
tick_count++;
printf("定时器触发: %d 次\n", tick_count);
}
int main(void)
{
// 创建周期定时器:每 100ms 触发一次
stru_task_timer_t pt = task_timer_create(
"heartbeat", on_tick, NULL, 100, TASK_TIMER_FLAG_PERIODIC
);
task_timer_start(pt);
task_sleep_ms(500); // 等待 500ms(预计触发 5 次)
task_timer_destroy(pt);
return 0;
}
事件
stru_task_event_t pe = task_event_create("ev1");
// 线程 A: 发送事件
task_event_send(pe, 0x03); // 设置 bit0 和 bit1
// 线程 B: 等待事件(OR 模式 + 自动清除)
uint32_t recved = 0;
task_event_recv(pe, 0x03,
TASK_EVENT_FLAG_OR | TASK_EVENT_FLAG_CLEAR,
TASK_EVENT_WAIT_FOREVER, &recved);
printf("收到事件: 0x%02X\n", recved); // 0x03
task_event_destroy(pe);
消息队列
// 创建队列:每条 64 字节,容量 10 条
stru_task_msg_queue_t pq = task_msg_queue_create("q1", 64, 10);
char tx[] = "Hello";
char rx[64];
task_msg_queue_send(pq, tx, 6); // 发送
task_msg_queue_recv(pq, rx, 64, 1000); // 接收(1 秒超时)
printf("收到: %s, 队列中: %u 条\n", rx, task_msg_queue_get_count(pq));
task_msg_queue_destroy(pq);
依赖关系
- 依赖: liblog (错误日志)
- 系统依赖:
<sys/timerfd.h>, <sys/epoll.h>, <sys/eventfd.h>, <pthread.h>
- 被依赖: 所有需要定时/同步/通讯的模块