The following example demonstrates the practical application and dynamic modification of task priorities and time quanta.
#include <stdio.h> #include "OS_API.h" volatile UINT32 FastCounter; volatile UINT32 SlowCounter; ERROR CountingTask(PVOID Arg) { /* Increment pointed counter */ while(1) (*(UINT32 FAR *) Arg)++; } ERROR TickerTask(PVOID Arg) { BOOL PrevLockState; /* Mark parameter as unused */ AR_UNUSED_PARAM(Arg); /* Show counters value for every 1/10 of second */ while(1) { /* Disable interrupts when printf function is used simultaneously */ PrevLockState = arLock(); /* Print message */ printf("fast counter: %lu\nslow counter: %lu\n\n", FastCounter, SlowCounter); /* Restore interrupts */ arRestore(PrevLockState); /* Sleep for 1/10 of second */ osSleep(AR_TICKS_PER_SECOND / 10); } } ERROR MainTask(PVOID Arg) { TIME Time; HANDLE FastTaskHandle; HANDLE SlowTaskHandle; HANDLE TickerTaskHandle; /* Mark parameter as unused */ AR_UNUSED_PARAM(Arg); /* Set counters value */ FastCounter = 0; SlowCounter = 0; /* Create two counting tasks. Both have priority lower than current, so will not run until this task will be blocked */ FastTaskHandle = osCreateTask(CountingTask, (PVOID) &FastCounter, 0, 3, FALSE); SlowTaskHandle = osCreateTask(CountingTask, (PVOID) &SlowCounter, 0, 3, FALSE); /* Set the number of CPU time slices (time quanta) assigned by scheduler for each task that is running. The FastCounter will be incremented 100 times more frequently */ osSetTaskQuantum(FastTaskHandle, 100); osSetTaskQuantum(SlowTaskHandle, 1); /* Create task, which will show counters value for every 1/10 of second */ TickerTaskHandle = osCreateTask(TickerTask, NULL, 0, 1, FALSE); /* Sleep for 3 seconds */ osSleep(3 * AR_TICKS_PER_SECOND); /* Increase priority of current task */ osSetTaskPriority(osGetTaskHandle(), 0); printf("Priority of the main task has been raised.\n"); /* Perform a long job for 3 seconds */ printf("Main task is performing a long job for 3 seconds.\n"); Time = arGetTickCount(); while(1) if(arGetTickCount() >= (Time + 3 * AR_TICKS_PER_SECOND)) break; /* Restoring the priority of the main task. */ printf("Restoring the priority of the main task.\n\n"); osSetTaskPriority(osGetTaskHandle(), 2); /* Sleep for 3 seconds */ osSleep(3 * AR_TICKS_PER_SECOND); /* Terminate all tasks */ osTerminateTask(FastTaskHandle); osTerminateTask(SlowTaskHandle); osTerminateTask(TickerTaskHandle); printf("All tasks has been terminated.\n"); return ERR_NO_ERROR; } int main(void) { /* Initialization */ arInit(); stInit(); osInit(); /* Create main task */ osCreateTask(MainTask, NULL, 0, 2, FALSE); /* Start the operating system */ osStart(); /* Deinitialization */ osDeinit(); arDeinit(); return 0; }