Start here
top without thread mode hides the real story.Thread scheduling (conceptual)
Runnable threads sit on runqueues; the kernel picks next to run based on policy (CFS for SCHED_OTHER, priority queues for RT). Affinity masks limit which CPUs a thread may use; cgroup quotas throttle groups of threads.
By the end of this page you should be able to
- Explain why TID matters for per-thread CPU stats.
- Name one reason to set CPU affinity for a latency-sensitive worker.
- Relate cgroup `cpu.max` / quota to scheduling delays.
Operating systems · Threads
Thread scheduling
How kernel picks among runnable threads
TL;DR
Thread scheduling is the same scheduler as processes on Linux, tasks compete by priority class (CFS nice, RT bands). User runtimes may add layers (GOMAXPROCS) but ultimately map runnable goroutines onto kernel threads.
Summary
Thread scheduling questions often test whether you separate language-level tasks from kernel tasks and whether you understand priority inversion and cgroup throttles as scheduling-adjacent controls.
Deeper narrative
Kernel schedules threads, not “processes,” as runnable units; nice values and cgroups apply per-thread fields on Linux. User runtimes can pin worker pools to cores to reduce migration and cache loss.
Mechanism (step by step)
Per-thread priority
SCHED_OTHER nice is per-thread; RT priorities likewise per-thread.
Affinity
`sched_setaffinity` masks which CPUs may run the thread.
cgroup cpu
Throttling uses cfs_quota_us per cgroup containing threads.
Work conservation
Idle CPU pulls highest vruntime runnable from shared or hierarchical runqueues.
Key insights
vruntime fairness
Runqueue migration
Kernel preemption
User runtime schedulers
Did you know?
Common pitfalls
Assuming PID is sched unit
Use TID for per-thread stats; `top -H` toggles thread mode.
Spinning without yielding
Busy-wait burns a core; pair with `sched_yield` only as last resort.
Comparison
Linux policy families (simplified)
| Policy | Intent |
|---|---|
| SCHED_OTHER (CFS) | Fair proportional sharing |
| SCHED_FIFO/RR | Real-time preemption bands |
| SCHED_IDLE | Only if nothing else runnable |
Glossary
Nice value
Affinity mask
CFS quota
Interview follow-ups
- How does CFS treat two threads of the same process vs two processes?
- What happens when RT threads starve kworkers?
- Why set cpu affinity for latency-sensitive threads?
Callouts
Perf
Off-CPU flame graphs reveal lock waits mistaken for “bad CPU scheduling.”
Walkthrough & deep dive
Left: practical “how would I use this?” threads. Right: slower, code-leaning explanations, open one panel at a time so the page does not feel like a wall of sameness.
Walkthrough
Scenario
Deep dive
Nice vs RT
Nice adjusts CFS weights; RT priorities are absolute preemption layers, mixing requires extreme care.
Affinity peek
taskset -cp $
Self-check
1CFS primarily targets…
2CPU cgroup throttling…
3SCHED_FIFO threads…