Skip to content

多任务

多任务模拟实现

C
  1 #include <stdio.h>                                                                    
  2 
  3 void delay(int ms)
  4 {
  5     for(int i = 0 ; i<5000000 ; i++)
  6     {
  7         for(int j = 0 ; j < ms ; j++);
  8     }
  9 }
 10 
 11 int task_key_scan(void)
 12 {
 13     int key_value;
 14     printf("keyboard scan...\n");
 15     return key_value;
 16 }
 17 void task_led_show(void)
 18 {
 19     printf("lec_show\n");
 20 }
 21 void task_temperature_get(void)
 22 {
 23     printf("DB18S20 init ...\n");
 24 }
 25 void task_temperature_set(void)
 26 {
 27     printf("set temperature...\n");
 28 }
 29 int main(void)
 30 {
 31     while(1)
 32     {
 33         task_temperature_get();
 34         delay(100);
 35         task_led_show();
 36         delay(100);
 37         task_key_scan();
 38         delay(100);
 39         task_temperature_set();
 40         delay(100);
 41         printf("\n\n");
 42 
 43     }
 44     return 0;
 45 }

改变频率

C
  1 #include <stdio.h>                                                                    
  2 
  3 unsigned int count;
  4 void count_add(void)
  5 {
  6     for(int i = 0;i<5000000;i++);
  7     count++;
  8 
  9 }
 10 
 11 int task_key_scan(void)
 12 {
 13     int key_value;
 14     printf("keyboard scan...\n");
 15     return key_value;
 16 }
 17 void task_led_show(void)
 18 {
 19     printf("lec_show\n");
 20 }
 21 void task_temperature_get(void)
 22 {
 23     printf("DB18S20 init ...\n");
 24 }
 25 void task_temperature_set(void)
 26 {
 27     printf("set temperature...\n");
 28 }
 29 int main(void)
 30 {
 31     while(1)
 32     {
 33         count_add();
 34         if(count % 1000 == 0)
 35             task_temperature_get();
 36         if(count %100 == 0)
 37             task_led_show();
 38         if(count % 200 == 0)
 39             task_key_scan();
 40         if(count % 2000 == 0)
 41             task_temperature_set();
 42         
 43     }
 44     return 0;
 45 }

改变任务执行时间

防止由于某些任务时间过长,影响其他任务的正常执行

使用状态机

记录每次的状态,根据状态进行处理,并转换至下一种状态