求赞qwq
众所周知,像STM32F10X系列之类的单片机都是单核的,要是不使用特殊手段,很难实现多个独立延时的LED灯的闪烁操作,对此我写了个线程表,等于硬件实现不了的L功能我用软件帮它实现qwq
接下来是代码以及代码讲解awa:
先发代码:
#include <stdio.h> typedef unsigned int time32_t;
typedef unsigned int u32_t;typedef struct {time32_t sleeptime;void(*runfun)();
} cpl_t;void __initcpl_t__(cpl_t* _obj, u32_t _ite) {if (_obj == NULL) return;while (_ite-- > 0) {_obj[_ite].runfun = NULL;_obj[_ite].sleeptime = 0; // 初始化为0 }
}void __insertcpl_t__(cpl_t* _obj, void(*runfun)(), time32_t sleeptime, u32_t _max) {if (_obj == NULL) return;u32_t i = 0;while (i < _max && _obj[i].sleeptime != 0) { // 检查sleeptime是否为0 i++;}if (i >= _max) return; // 防止越界 _obj[i].runfun = runfun;_obj[i].sleeptime = sleeptime;
}void __showcpl_t__(cpl_t* _obj, u32_t _max, time32_t jishi, time32_t sleep, void (*clear)()) {if (_obj == NULL) return;time32_t i = sleep;for (time32_t count = 0 ; count < jishi; count++) {for (u32_t temp = 0 ; temp < _max ; temp++) {if (_obj[temp].sleeptime != 0 && count % _obj[temp].sleeptime == 0 && _obj[temp].runfun != NULL /*count != 0*/) {_obj[temp].runfun();printf("当前时间刻:%d\n", count);}}clear(); // 调用清除函数 }
}void task1() {printf("Task 1 is running\n");
}void task2() {printf("Task 2 is running\n");
}void clear() {printf("Clearing...\n"); // 添加清理输出
}// 主程序
int main() {const u32_t max_tasks = 5;cpl_t tasks[5];// 初始化任务 __initcpl_t__(tasks, max_tasks);// 插入任务 __insertcpl_t__(tasks, task1, 2, max_tasks); // 每 2 个时间单位运行一次 __insertcpl_t__(tasks, task2, 3, max_tasks); // 每 3 个时间单位运行一次 // 模拟多线程行为 printf("Starting task simulation...\n");//快说,谢谢GPT爸爸的翻译qwq__showcpl_t__(tasks, max_tasks, 20, 100, clear); // 假设执行 20 个时间单位 return 0;
}
(博客选择不了C语言,所以选了C++)
可以看到,十分简洁的调库列表,绝对没有偷偷使用标准库qwq.
(灵感和思路是从石头缝里蹦出来的)
首先是对结构体的定义,其实这个结构体是用来做数组用的,结构体数组本质上就是几个数组的集合,是个人都懂好qwq.
(初始化没必要讲awa)
插入函数和链表的没有太大的区别,只是主体是数组.就是找下一个没被存东西过的空位,然后把插入的线程的延时,执行的函数插入到数组里,秒!
接下来就是最L的函数了,主要就是定个软件计时器用来定位时间刻,然后在刚才讲到的存储函数和延时时间的数组中翻箱倒柜,找到延迟时间是当前时间刻因数的对象,执行这个对象里的函数.如果想要更快的速度,可以把线性查找换成更快的查找结构或哈希表(当然我这个不是为了时间)qwq
散会awa_