context swithing

 

What is Context Switching in Linux?

Context switching is the process of saving the state of a currently running process or thread, so that another process/thread can run, and later restoring the saved state to resume execution.

It allows multitasking and CPU sharing among many processes.


🔧 When Does Context Switching Occur?

  • Voluntarily by the process (e.g. sleep(), read())

  • Involuntarily due to:

    • Time slice expiration (preemptive scheduling)

    • I/O wait

    • Higher priority process ready

    • Interrupts

    • Signals


🧱 Types of Context Switches

Type

Description

Process-to-process

Full state change (registers, memory map, page tables, FPU, etc.)

Thread-to-thread (same process)

Minimal change (no MMU change)

Kernel-to-user / user-to-kernel

Happens during syscalls, traps, or interrupts


🧩 What Gets Saved in a Context Switch?

  • CPU registers (RIP, RSP, general-purpose)

  • Stack pointer

  • Program counter (Instruction pointer)

  • MMU state (page table pointers)

  • FPU state

  • Process control block (PCB)

  • Kernel mode/user mode switch


🏎️ Cost of Context Switching

Context switching is expensive (~1µs to 10µs or more) because:

  • Cache (L1/L2) is flushed

  • TLB might be invalidated

  • Scheduler overhead

  • Kernel bookkeeping

➡️ Too many context switches = performance bottleneck


🔍 Measure Context Switches

1. vmstat:

vmstat 1


Look at cs (context switches per second)


2. pidstat:

pidstat -w -p <PID> 1



3. perf:

perf stat -e context-switches -p <PID>



4. /proc filesystem:

cat /proc/<pid>/status | grep ctxt



📉 Reduce Context Switching

  • Use cooperative multitasking (green threads)

  • Avoid excessive thread creation

  • Use thread pools

  • Use async IO (epoll, select, io_uring)

  • Optimize CPU affinity and scheduling policy

  • Avoid busy waiting or spinlocks when possible


⚔️ Context Switching vs Preemption vs Interrupts

Concept

Trigger

Example

Context switch

Scheduler decides to switch

After time slice

Preemption

Higher priority task arrives

Real-time interrupt

Interrupt

Hardware triggers kernel handler

Keyboard press


🧠 20 FAANG-Level Context Switching Questions (Categorized)


🟢 Beginner

Q1. What is context switching?

A: Saving and restoring a CPU's state to switch between tasks.


Q2. Why is context switching necessary in OS?

A: To enable multitasking and allow multiple processes to share CPU.


Q3. What gets saved during a context switch?

A: CPU registers, stack pointer, program counter, page table pointer, etc.


Q4. How does context switching relate to threads?

A: Thread context switch is cheaper than process switch due to shared address space.


Q5. How to view context switches using vmstat?

vmstat 1


Column cs shows context switches per second.


🟡 Intermediate

Q6. How is context switching handled in Linux kernel?

A: Through the scheduler (like CFS), which uses schedule() to pick next task.


Q7. What's the overhead of context switching?

A: ~1-10µs depending on hardware; includes cache/TLB flushing, scheduler cost.


Q8. How does thread affinity affect context switches?

A: Pinning threads to cores reduces migration and unnecessary context switching.


Q9. How does nice value affect context switching?

A: It influences scheduling priority and frequency of getting CPU time.


Q10. Difference between user→kernel switch and process switch?

A:

  • User→kernel: Happens in the same thread (e.g., read())

  • Process switch: Scheduler switches entire processes


🔴 Advanced / FAANG-Level Debugging

Q11. Context switching vs interrupt handling?

A: Interrupts are hardware-triggered and can lead to context switches if scheduling decisions are made post-interrupt.


Q12. How can context switching degrade performance in high-concurrency systems?

A: High switch rate causes:

  • Cache misses

  • TLB flushes

  • Lower throughput


Q13. How can you reduce context switching in a high-throughput server?

A:

  • Use epoll/io_uring for async I/O

  • Fewer threads

  • Thread pools

  • Core pinning

  • Real-time scheduling (SCHED_FIFO)


Q14. Which system calls can cause context switching?

A:

  • read(), write(), sleep(), wait(), select(), poll(), nanosleep()


Q15. How to detect high context switching in production?

A:

  • vmstat, perf, pidstat, sar

  • Use BPF tools (bcc, bpftrace) to trace kernel events


Q16. What’s the role of the schedule() function in the Linux kernel?

A:
Performs the actual context switch by saving the current task and restoring the next runnable task.


Q17. What is "voluntary context switch" vs "involuntary" in /proc/<pid>/status?

A:

  • Voluntary: Process gives up CPU willingly (e.g., I/O wait)

  • Involuntary: Scheduler forces switch due to preemption


Q18. How does futex avoid unnecessary context switches?

A:

  • It tries to resolve locks in userspace first.

  • Only enters kernel if contention exists → reduces switching


Q19. How does NUMA affect context switching and performance?

A:

  • Cross-node memory access during switching can increase latency.

  • Scheduler tries to optimize locality (via numactl or CPU sets)


Q20. How does Linux ensure fairness in scheduling and context switching?

A:

  • Completely Fair Scheduler (CFS)

  • Tracks virtual runtime (vruntime)

  • Prioritizes the task that had the least CPU time


✅ Summary Table

Feature

Detail

Saves

Registers, PC, stack, MMU state

Cost

High (~1-10µs)

Trigger

Scheduler, I/O, signals, timer, preemption

View

vmstat, perf, /proc, pidstat

Optimize

Async I/O, thread pools, core pinning



Distributed by Gooyaabi Templates | Designed by OddThemes