- /*
- 定义线程函数
- */
- typedef void(*thread_fun)(void);
- /*
- 保存一个线程的状态信息
- num: 为该线程一次执行的次数,一般为1,代表执行频率是1
- count: 线程执行的数量,当为负值时代表线程挂起的次数,为正数表示开始执行
- sleep: 是否休眠结束
- */
- class Thread
- {
- public:
- int num;
- int count;
- int sleep;
- Thread()
- {
- sleep=0;
- }
- Thread(int n,int c):num(n),count(c)
- {
- }
- thread_fun fun;
- };
- #define MAX_THREAD_NUM 10 //定义最大线程数
- static int threadIndexNum; //保存当前线程的实际数量
- static Thread* threads[MAX_THREAD_NUM]; //线程
- static Thread* currentThread; //表示当前正在执行的线程
- static int Init() //线程的初始化
- {
- threadIndexNum=0;
- }
- /*
- 创建一个新线程,线程函数格式为 void f()
- */
- static int attachThreadFunc(void (*f)())
- {
- threads[threadIndexNum]=new Thread();
- threads[threadIndexNum]->fun=f;
- threadIndexNum++;
- if(threadIndexNum>MAX_THREAD_NUM)
- threadIndexNum--;
- }
- /*
- 进入线程执行的总循环
- */
- static void Run()
- {
- unsigned int i=0;
- for(i=0;i<threadIndexNum;++i)
- {
- currentThread=threads[i];
- if(threads[i]->count>0)
- {
- threads[i]->num=1;
- threads[i]->count--;
- threads[i]->fun();
- }
- threads[i]->count++;
- delay(1);
- }
- }
- /*
- 线程内部所使用的while,宏定义使其能够跳出进行其他线程的循环
- */
- #define WHILE(x) if(currentThread->sleep) \\
- goto thislabel1; \\
- while((x)&&(currentThread->num-->0))
- /*
- 线程内部使用的sleep,代表线程挂起多少毫秒,推荐线程内部不使用delay,因为会影响所有的线程循环队列,使用DELAY可近似地延时相应的毫秒数,必须和WHILE配合使用
- */
- #define SLEEP(n) { \\
- currentThread->count-=n; \\
- currentThread->sleep=true; \\
- break; \\
- thislabel1: \\
- currentThread->sleep=false; \\
- }
- #define ENDSLEEP currentThread->sleep=1 \\
- /*线程函数1*/
- void fun1()
- {
- WHILE(1){
- Serial.println("hello,fun1");
- SLEEP(300);
- }
- }
- /*线程函数2*/
- void fun2()
- {
- WHILE(1){
- Serial.println("hello,fun2");
- SLEEP(500);
- }
- }
- void setup()
- {
- Serial.begin(9600);
- Init(); //初始化线程
- attachThreadFunc(&fun1);//创建线程1
- Serial.println("fun1 over");
- attachThreadFunc(&fun2);//创建线程2
- Serial.println("fun2 over");
- }
- void loop()
- {
- Run();//开始一次线程循环
- }
- //该片段来自于http://www.codesnippet.cn/detail/2808201410364.html
来源: http://www.codesnippet.cn/detail/2808201410364.html