Tuesday, November 26, 2013

Time Slice Multitasking

This is a code example of time slice multitasking in C.

#include
#define KERNEL_SLEEP_US 1000
#define msleep(x) sleepc++; if(sleepc != x){return;}else{sleepc=0;}
int program_end = 0;

void task1(void) {
static int pc=0,sleepc=0;
switch (pc){
case 0: goto label0;
case 1: goto label1;
case 2: goto label2;
case 3: goto label3;
case 4: goto label4;
case 5: goto label5;
case 6: goto label6;
case 7: goto label7;
default: return;
}                                   // task code section
                                       // ========================================= 
label0:               /* a task code -> */ while(1){
pc=1; return; label1: /* a task code -> */   
pc=2; return; label2: /* a task code -> */   
pc=3; return; label3: /* a task code -> */   
pc=4; return; label4: /* a task code -> */   
pc=5; return; label5: /* a task code -> */   printf("Hello from task 1\n");
pc=6; return; label6: /* a task code -> */   msleep(250);  }
pc=7; return; label7: /* a task code -> */   
pc=8; return;                           // ========================================      
}

void task2(void) {
static int pc=0,sleepc=0,ii;
switch (pc){
case 0: goto label0;
case 1: goto label1;
case 2: goto label2;
case 3: goto label3;
case 4: goto label4;
case 5: goto label5;
case 6: goto label6;
case 7: goto label7;
default: return;
}                                   // task code section
                                       // ========================================= 
label0:               /* a task code -> */   for(ii=0;ii<5 font="" ii="">
pc=1; return; label1: /* a task code -> */     printf("<<-- --="" 2="" d="" font="" ii="" n="" task="">
pc=2; return; label2: /* a task code -> */     msleep(1000); };
pc=3; return; label3: /* a task code -> */   
pc=4; return; label4: /* a task code -> */   program_end = 1;
pc=5; return; label5: /* a task code -> */   
pc=6; return; label6: /* a task code -> */   
pc=7; return; label7: /* a task code -> */   
pc=8; return;                           // =========================================        
}

my_kernel(){
  usleep(KERNEL_SLEEP_US); // sleep 100 ms
}

int main(void)
{
  while(!program_end)
  {
  task1();
  task2();
  my_kernel();
  }
    return 0;
}

No comments:

Post a Comment