Does changing thread priority deschedule a thread immediately?

Viewed 62

I'm trying to perform concurrency testing of a concurrent data structure. My strategy is to run the test on many threads and hope for as many context switches as possible. Every context switch is an opportunity for a race condition to manifest.

Since I'm using .NET I have no (supported) way of suspending threads. My idea is that I can use the thread priority to induce context switches. I'd randomly and frequently change the thread priority to rip threads off their CPU cores. (I believe this question is not materially related to .NET).

Is changing the thread priority immediately respected by the OS scheduler? Or is the current time quantum allowed to run to completion? If the quantum runs to completion then this strategy would not help.

1 Answers

TL;DR: A context switch can be performed on Windows, but more generally, it is dependent of the platform and may also change in the future.

This is possible but totally dependent of the implementation the OS scheduler. Its behaviour can change from one OS to another and even be different on two machine with the same OS (AFAIK Linux supports for example different schedulers). Generally, the OS tends not to interrupt the quantum allowed to a process unless high-priority events occurs (eg. IOs) or the process perform a task that can take a long time (eg. sleeping for a given time, waiting on condition variables, waiting on a locks). That being said, many schedulers use a kind of process priority queue and could do a context switch (generally only) if a process with a higher priority is ready. Thus, setting the priority can cause a context switch in such a case.

On Windows, you can find information about priority and the scheduler behaviour here and there. There is also additional information about when context switches are performed here. More specifically, the documentation explicitly states:

The most common reasons for a context switch are:

  • The time slice has elapsed.
  • A thread with a higher priority has become ready to run.
  • A running thread needs to wait.
Related