Suppose a running Java application have two concurrent threads with the same
priority, and no other user threads exist in the application. If we want to
calculate how many times the context switch happens between these two
threads, or we want to count how many times each thread is interrupted, with
what APIs or how can we do this job?
If you are just trying to figure out what the overhead is when the
system decides to switch threads, and so the threads don't have to be
doing useful work, something like this might work.
1. Give each thread an ID number.
2. Have a variable, cur_thread.
3. Each thread does something like this (psuedocode):
int switchcount = 0
while (true) {
if ( cur_thread != our thread ID )
++switchcount
cur_thread = our thread ID
}
In switchcount, you should have a close approximation at any given time
of the number of times there was a context switch from this thread.
If you put cur_thread in shared memory, you can use this same technique
on many systems to also get process switch counts.
You can also get context switch times by adding an array that has one
entry per thread. In that array, the thread, each time through the
loop, writes the current time. When the thread sees that cur_thread is
not its own ID, it can use cur_thread to look in that array for the last
time the other thread ran, and subtract from the current time, to get
the context switch time.
Note that it is quite possible that context switch times when the
context switch is due to a preemptive thread or process switch could
well be quite different from context switch times when a thread or
process does an operation that yields, so don't try to use any benchmark
results such as these where they are not appropriate.