How expensive are kernel context switches compared to userspace context switches? How expensive are kernel context switches compared to userspace context switches? multithreading multithreading

How expensive are kernel context switches compared to userspace context switches?


  • Why are these userspace context switches faster than kernel thread context switches?

Because the CPU does not need to switch to kernel mode and back to user mode.

  • What exactly does a kernel context switch do that's so much more expensive?

Mostly the switch to kernel mode. IIRC, the page tables are the same in kernel mode and user mode in Linux, so at least there is no TLB invalidation penalty.

  • How expensive is a kernel context switch exactly? How much time does it take?

Needs to be measured and can vary from machine to machine. I guess that a typical desktop/server machine these days can do a few hundred thousands of context switches per second, probably a few million.

  • Does kernel context switching time depend on the number of threads?

Depends on how the kernel scheduler handles this. AFAIK, in Linux it is pretty efficient, even with large thread counts, but more threads means more memory usage means more cache pressure and thus likely lower performance. I also expect some overhead involved in the handling of thousands of sockets.