The following example demonstrates how to create a task, ensure its proper completion, and perform task termination of one task by another.
#include <stdio.h> #include "OS_API.h" ERROR WorkerTask(PVOID Arg) { TIME StartTime; /* Mark parameter as unused */ AR_UNUSED_PARAM(Arg); /* Welcome message */ printf(" Worker task is started.\n"); /* Perform a long job for 3 seconds */ printf(" Worker is performing a long job for 3 seconds.\n"); StartTime = arGetTickCount(); while(1) if(arGetTickCount() >= (StartTime + 3 * AR_TICKS_PER_SECOND)) break; /* Finish worker task */ printf(" Worker finishes work.\n"); return ERR_NO_ERROR; } ERROR MainTask(PVOID Arg) { HANDLE TaskHandle; /* Mark parameter as unused */ AR_UNUSED_PARAM(Arg); /* Welcome message */ printf("Main task is started.\n"); /* Create worker task with higher priority */ printf("Create worker task with higher priority.\n"); TaskHandle = osCreateTask(WorkerTask, NULL, 0, 0, FALSE); if(!TaskHandle) { printf("Cannot create worker task.\n"); osExitTask(osGetLatError()); } /* The new task has been created with a higher priority than the priority of current task. The following instructions will be executed when a new task is completed. */ printf("Worker task is finished.\n"); osCloseHandle(TaskHandle); /* Create worker task with lower priority */ printf("Create worker task with lower priority.\n"); TaskHandle = osCreateTask(WorkerTask, NULL, 0, 2, FALSE); if(!TaskHandle) { printf("Cannot create worker task.\n"); osExitTask(osGetLatError()); } /* The new task has lower priority than the current task, therefore will run only when the current task is blocked (e.g. by waiting for this task completion. Wait one second for worker task */ printf("Wait one second for worker task.\n"); osWaitForObject(TaskHandle, 1 * AR_TICKS_PER_SECOND); /* Terminate worker task */ printf("Terminate worker task.\n"); osTerminateTask(TaskHandle); /* Finish main task */ printf("osExitTask() function called for main task.\n"); osExitTask(ERR_NO_ERROR); /* The following instructions will not be executed */ printf("Main task finishes work.\n"); return ERR_NO_ERROR; } int main(void) { /* Initialization */ arInit(); stInit(); osInit(); /* Create main task */ osCreateTask(MainTask, NULL, 0, 1, FALSE); /* Start the operating system */ printf("Starting the operating system...\n"); osStart(); /* Deinitialization */ osDeinit(); arDeinit(); return 0; }
The expected console output is as follows:
Starting the operating system... Main task is started. Create worker task with higher priority. Worker task is started. Worker is performing a long job for 3 seconds. Worker finishes work. Worker task is finished. Create worker task with lower priority. Wait one second for worker task. Worker task is started. Worker is performing a long job for 3 seconds. Terminate worker task. osExitTask() function called for main task.