用C语言编写一个定时器队列的接口函数,可注册多个任务,并对每个任务进行不同事件的轮询执行
时间: 2024-05-06 16:19:27 浏览: 100
STM32F1C6T6时间片轮询多任务
很高兴为您解答这个问题!
以下是用C语言编写一个定时器队列的接口函数的示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义定时器结构体
typedef struct _timer {
int id; // 定时器ID
int interval; // 定时器间隔时间
int count; // 定时器计数器
void (*callback)(void *ctx); // 回调函数
void *ctx; // 回调函数上下文
struct _timer *next; // 指向下一个定时器的指针
} timer_t;
// 定义定时器队列结构体
typedef struct _timer_queue {
int count; // 定时器数量
timer_t *head; // 指向第一个定时器的指针
} timer_queue_t;
// 初始化定时器队列
void timer_queue_init(timer_queue_t *queue) {
queue->count = 0;
queue->head = NULL;
}
// 添加定时器
void timer_queue_add(timer_queue_t *queue, int id, int interval, void (*callback)(void *ctx), void *ctx) {
// 创建新定时器
timer_t *timer = (timer_t *)malloc(sizeof(timer_t));
timer->id = id;
timer->interval = interval;
timer->count = interval;
timer->callback = callback;
timer->ctx = ctx;
timer->next = NULL;
// 添加到队列
if (queue->head == NULL) {
queue->head = timer;
} else {
timer_t *tail = queue->head;
while (tail->next != NULL) {
tail = tail->next;
}
tail->next = timer;
}
queue->count++;
}
// 注销定时器
void timer_queue_remove(timer_queue_t *queue, int id) {
timer_t *prev = NULL;
timer_t *curr = queue->head;
while (curr != NULL) {
if (curr->id == id) {
if (prev == NULL) {
queue->head = curr->next;
} else {
prev->next = curr->next;
}
free(curr);
queue->count--;
break;
}
prev = curr;
curr = curr->next;
}
}
// 执行定时器
void timer_queue_poll(timer_queue_t *queue) {
timer_t *prev = NULL;
timer_t *curr = queue->head;
while (curr != NULL) {
curr->count--;
if (curr->count == 0) {
curr->callback(curr->ctx);
curr->count = curr->interval;
if (curr->interval <= 0) {
if (prev == NULL) {
queue->head = curr->next;
} else {
prev->next = curr->next;
}
timer_t *next = curr->next;
free(curr);
curr = next;
queue->count--;
continue;
}
}
prev = curr;
curr = curr->next;
}
}
// 测试函数,打印字符串
void test_timer_callback(void *ctx) {
char *str = (char *)ctx;
printf("%s\n", str);
}
int main() {
timer_queue_t queue;
timer_queue_init(&queue);
// 添加两个定时器
timer_queue_add(&queue, 1, 10, test_timer_callback, "This is the first timer.");
timer_queue_add(&queue, 2, 20, test_timer_callback, "This is the second timer.");
// 循环执行定时器
for (int i = 0; i < 100; i++) {
timer_queue_poll(&queue);
}
// 注销定时器
timer_queue_remove(&queue, 1);
timer_queue_remove(&queue, 2);
return 0;
}
```
上面的示例代码实现了一个简单的定时器队列,可以添加、注销和执行多个定时器任务,并对每个任务进行不同事件的轮询执行。准确来说,它是一个基于链表的定时器实现,没有使用系统提供的定时器API函数。
阅读全文