Search code examples
c++cmultithreadingtaskvxworks

When do task based applications switch context?


Let's say you had two tasks. Each one has it's own complex modules running schedule based systems and event based systems. When thinking about context switching, exactly when and how does a task scheduler decide when to switch tasks, and at one point can it do this? Will a task switch while in the middle of executing a block of code? Right in the middle of a function?

For reference I am working in a vxworks environment.


Solution

  • Generally, operating system schedules have no concern for blocks of C code. They switch when various events occur including:

    • A timer measuring how long your process has been using the CPU expires.
    • A device connected to the computer reports it has completed a task, and some process with high priority than yours was waiting for this.
    • Your process makes a request that cannot be satisfied immediately, such as requesting input from the keyboard, and the user has not typed it yet.

    In the last case, the switch of course occurs at the point of your request. The others are effectively random with regard to where your process is executing. The associated interrupt can occur at any instruction in your process.

    In some processor architectures, an interrupt can even occur during certain instructions: The instruction may be interrupted when it has only been partially executed, and the registers will be updated so that execution can be resumed to continue the instruction later.