Is switching between threads much more efficient than processes in Linux?

183 Views Asked by At

From this question we know that both thread and process are treated as same schedule units in kernel and have little difference in scheduling scheme. However, I'm curious about the general cost of switching between threads and processes.

For example, when switching between 2 different processes, the kernel need to change the PTBR (in x86 is the CR3 Register) to switch process page table, causing the TLB to be re-flushed. But switching between different threads of same process seem to be free from such extra cost, since such threads should share the same virtual address space.

1

There are 1 best solutions below

0
On

The main cost in both scenarios is related to a cache pollution. In most cases, the working set used by the outgoing thread will differ significantly from working set which is used by the incoming thread. As a result, the incoming thread will start its life with avalanche of cache misses, thus flushing old and useless data from the caches and loading the new data from memory. The same is true for TLB (Translation Look Aside Buffer, which is on the CPU). In the case of reset of virtual address space (threads run in different processes) the penalty is even worse, because reset of virtual address space leads to the flushing of the entire TLB, even if new thread actually needs to load only few new entries. As a result, the new thread will start its time quantum with lots TLB misses and frequent page walking. Direct cost of threads switch is also not negligible (from ~250 and up to ~1500-2000 cycles) and depends on the CPU complexity, states of both threads and sets of registers which they actually use.

P.S.: Good post about context switch overhead: http://blog.tsunanet.net/2010/11/how-long-does-it-take-to-make-context.html