线程池会导致上下文切换开销吗?

时间:2016-03-04 17:39:46

标签: multithreading threadpool

当一个线程在已经提交给线程池的任务之间切换时,是否会产生上下文切换开销(或者类似的东西)?

1 个答案:

答案 0 :(得分:1)

No. Context switch is a process of storing and restoring state of a thread. This is important when you have more threads then your CPU supports. So that your OS can emulate many threads over small number of physical threads. Simply speaking more threads == more overhead because context switch has to occure more often (so that we still have ilusion of things happening parallely). Up to a point when it crashes your system. :)

However when a thread switches between tasks then these tasks have to be stored somewhere. This is usually done by a queue. So from thread's point of view this is simply queue.pop() and continue processing.

Now no matter what the implementation of the queue is there has to be a consistency and atomicity guarantee of .pop() operation. Such a guarantee always comes with a small (or big, implementation dependent) overhead.

So yes, switching between tasks comes with a performance hit, but this has nothing to do with context switch.