Reputation: 5236
I've been testing out some code that uses ThreadPool
in C# and I noticed that a lot of unnecessary context switch occurs. While one thread is executing regular statements it gets context switched. They literally seem to be going back and forth for every line. I was wondering what the logic behind this was. Why would a thread get switched out for regular executions?
Upvotes: 4
Views: 1283
Reputation: 97701
Threads are supposed to execute simultaneously, running both threads at "the same time". In reality, each thread (on a single processor computer) gets a finite amount of time (called a quantum) which is executed before a context switch. This is a gross oversimplification, of course, but basically this is what happens.
When you run both threads in the debugger and step through (which is what I guess you're doing), the act of stepping through each statement causes it to exceed the time the thread has for its execution, and you get a context switch back to the other thread.
Upvotes: 4
Reputation: 174329
While stepping through your code in debugging, every line takes WAY longer than during normal execution. That's why there are so many context switches. Normally, they happen multiple times per second.
Upvotes: 2