π Introduction #
In the previous blog Getting Started with VxWorks Programming: Hello World for Beginners, we wrote our first Hello World program in VxWorks and learned about tasks.
Now, itβs time to dive deeper into:
- How tasks are created and managed in VxWorks.
- Task priorities and preemptive scheduling.
- Writing a program with multiple tasks to see scheduling in action.
π§© What Are Tasks in VxWorks? #
In VxWorks, a task is the smallest unit of execution β similar to a thread in other systems.
Each task has:
- A priority (0β255, where 0 = highest priority).
- A stack (memory allocated for execution).
- A state (ready, running, suspended, or delayed).
The VxWorks scheduler always runs the highest-priority ready task. If a higher-priority task becomes ready, it preempts (interrupts) the currently running task.
π» Example: Multiple Tasks with Different Priorities #
Letβs write a program that spawns two tasks β one with high priority and one with low priority.
Code Example #
#include <vxWorks.h>
#include <taskLib.h>
#include <stdio.h>
#include <unistd.h>
// High-priority task
void highPriorityTask()
{
while (1)
{
printf("High Priority Task is running...\n");
sleep(1); // Delay for 1 second
}
}
// Low-priority task
void lowPriorityTask()
{
while (1)
{
printf("Low Priority Task is running...\n");
sleep(1); // Delay for 1 second
}
}
void usrAppInit(void)
{
// Spawn high-priority task
taskSpawn("tHigh", 50, 0, 2000, (FUNCPTR)highPriorityTask,
0,0,0,0,0,0,0,0,0,0);
// Spawn low-priority task
taskSpawn("tLow", 150, 0, 2000, (FUNCPTR)lowPriorityTask,
0,0,0,0,0,0,0,0,0,0);
}
π Explanation of the Code #
-
Two Tasks
highPriorityTask()
prints a message every second.lowPriorityTask()
does the same.
-
taskSpawn()
"tHigh"
is given priority50
(higher)."tLow"
is given priority150
(lower).
-
Preemptive Scheduling
- Since
tHigh
has a higher priority, it will always run when it is ready. tLow
only runs whentHigh
is delayed (sleep(1)
gives it time).
- Since
β‘ What Youβll See #
When you run this code, the output will look like:
High Priority Task is running...
Low Priority Task is running...
High Priority Task is running...
Low Priority Task is running...
...
Notice how the low-priority task only executes when the high-priority task yields (via sleep).
π Key Takeaways #
- VxWorks uses priority-based preemptive scheduling.
- A higher-priority task always runs first.
- Lower-priority tasks only run when higher-priority tasks are idle or delayed.
β Wrap-Up #
In this tutorial, we explored:
- How VxWorks creates and manages multiple tasks.
- How task priorities affect execution.
- How preemptive scheduling ensures deterministic behavior.
In the next blog, weβll cover inter-task communication using semaphores to coordinate between tasks.
π Stay tuned for Blog 3: βUsing Semaphores for Task Synchronization in VxWorks.β