4

Background

Okay, so let's say I have some high priority (ThreadPriority.Highest) thread t which needs to enter a critical region in order to consume some data. I will use the following code snippet to illustrate my point.

// create a consumer thread
t = new Thread(() =>
{
    Monitor.Enter(myLock);

    // consume data

    Monitor.Exit(myLock);
});
t.Name = "Data Consumer";
t.Priority = ThreadPriority.Highest;
t.Start();

In the above example, the thread attempts to enter the region in order to consume the data (when the lock is available).

Question

Are there any performance implications I need to know about when a thread of highest priority is entering the region v.s. a lower-priority thread trying to enter the region?

For instance, let's say that the highest priority thread is not able to obtain the myLock because there is some other thread busy with the region. Is the thread with ThreadPriority.Highest going to consume a lot more CPU when trying to enter the region (as compared with a lower-priority thread)?

  • Hvae a look at the code sample here: msdn.microsoft.com/en-us/library/… – Robert Harvey Jun 10 '16 at 14:44
  • @RobertHarvey interesting, yeah the AboveNormal thread does seem to get more access to the loop. I guess that would remain true whether or not the region is locked? – Snoop Jun 10 '16 at 14:47
  • Yes, it would... – Robert Harvey Jun 10 '16 at 15:02
  • The main problem is CPU starving the lower priority thread. You did not explain why you use different priorities. There is no more or less CPU used per thread unless you unblock them and let them run freely. – Frank Hileman Jun 14 '16 at 0:52
1

Are there any performance implications I need to know about when a thread of highest priority is entering the region v.s. a lower-priority thread trying to enter the region?

A well-known problem with this situation is priority inversion: if a low-priority thread holds the lock, it may make the high-priority thread wait for a long time (because medium-priority threads are being scheduled). But operating system authors are aware of this and tend to have solutions for it.

For instance, let's say that the highest priority thread is not able to obtain the myLock because there is some other thread busy with the region. Is the thread with ThreadPriority.Highest going to consume a lot more CPU when trying to enter the region (as compared with a lower-priority thread)?

No, the process of taking the lock does not depend on thread priority. If the lock is taken, the thread won't consume much CPU and will pretty quickly transition to a sleep state.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.