What is pre-emptive versus cooperative scheduling?
Short answer: With pre-emptive scheduling, the kernel switches to a higher-priority task as soon as it becomes ready (because of an interrupt, a timer or another task), even in the middle of the current task's code. With cooperative scheduling, a task keeps the CPU until it voluntarily yields or blocks. Pre-emption gives better worst-case response for urgent work; cooperative scheduling is simpler and needs fewer locks, but one task that does not yield stalls everything.
| Pre-emptive | Cooperative | |
|---|---|---|
| When switches happen | any time a higher-priority task is ready | only at taskYIELD(), blocking calls, or task return |
| Response time for urgent work | bounded by kernel latency | bounded by the longest code between yields |
| Shared data protection | needed everywhere data is shared | only needed around yield points (and with ISRs) |
| Risk | race conditions, priority inversion | one long-running task blocks all others |
| FreeRTOS | configUSE_PREEMPTION 1 |
configUSE_PREEMPTION 0 |
How pre-emption happens on Cortex-M: an ISR (or a task) makes a higher-priority task ready → the kernel pends PendSV → when all ISRs finish, PendSV switches context.
Mixed approaches
- FreeRTOS: pre-emptive between priorities, with optional time slicing between equal priorities.
- Zephyr: cooperative threads (negative priorities) cannot be pre-empted by other threads, which is useful for code that must not be interrupted by other threads but still allows ISRs; pre-emptible threads (non-negative priorities).
- Event-driven "run-to-completion" frameworks (QP active objects) are cooperative inside each object but can use pre-emption between objects.
Interview angle: most products use pre-emptive scheduling for responsiveness, plus good discipline: short critical sections, message passing, and correct priorities.