Jeff Atwood has a blog post entitled Thread Priorities are Evil where he writes
Joe Duffy is something of an expert on the topic of threading and concurrency--
he works for Microsoft on CPU-based parallelism in the .NET Common Language
Runtime-- and he has this
to say:
Messing with [thread] priorities is actually a very dangerous
practice, and this is only one illustration of what can go wrong. (Other
illustrations are topics for another day.) In summary, plenty of people do it
and so reusable libraries need to be somewhat resilient to it; otherwise, we get
bugs from customers who have some valid scenario for swapping around priorities,
and then we as library developers end up fixing them in service packs. It's less
costly to write the right code in the first place.
Here's the problem. If somebody begins the work that will make 'cond' true on
a lower priority thread (the producer), and then the timing of the program is
such that the higher priority thread that issues this spinning (the consumer)
gets scheduled, the consumer will starve the producer completely. This is a
classic race. And even though there's an explicit Sleep in there, issuing it
doesn't allow the producer to be scheduled because it's at a lower priority. The
consumer will just spin forever and unless a free CPU opens up, the producer
will never produce. Oops!
The moral of the story? [Thread] priorities are evil, don't mess with
them.
Although there are some edge conditions where micromanaging thread priorities
can make sense, it's generally a bad idea. Set up your threads at normal
priority and let the operating system deal with scheduling them. No matter
how brilliant a programmer you may be, I can practically guarantee you won't be
able to outsmart the programmers who wrote the scheduler in your operating
system.
On reviewing the RSS Bandit code it seems that we use ThreadPriority.BelowNormal
and ThreadPriority.Lowest
in a bunch of places which may cause the kind of deadlocks Joe Duffy describes. This is yet another example of why multithreaded programming is the spawn of Satan.