Starvation occurs when one thread or group monopolizes a required resource, preventing another thread from making progress. A lock held indefinitely can block every competing operation, while a continuously running high-priority thread can deprive lower-priority work of CPU time. section 7.6
Recognize starvation through these patterns:
- A thread acquires a lock before an infinite loop and never releases it, so competing lock attempts never succeed. section 7.6
- A continuously running high-priority thread can prevent lower-priority threads from receiving enough processor time. section 7.6
- Reduce the risk by holding locks for the shortest duration possible; excessive lock duration can turn synchronization into starvation. section 7.6
Listing 7.14 Starvation due to locking
using System.Diagnostics;
var theLock = new object();
var thread1 = new Thread(() =>
{
lock(theLock)
{
while (true)
{
Console.Write("-");
}
}
});
thread1.Start();
var thread2 = new Thread(() =>
{
while (true)
{
lock (theLock)
{
Console.Write("x");
}
}
});
thread2.Start();
Demonstrates lock-based starvation with two infinite loops: one prints only minus signs while retaining the lock, and the other never prints its x characters. section 7.6
Listing 7.15 Starvation due to thread priority
using System.Diagnostics;
Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(1); #1
var thread1 = new Thread(() =>
{
while (true)
{
Console.Write("-");
}
});
thread1.Start();
var thread2 = new Thread(() =>
{
while (true)
{
Console.Write("x");
}
});
thread2.Priority = ThreadPriority.AboveNormal; #2
thread2.Start();
Demonstrates CPU starvation by restricting execution to one processor core and raising one thread to AboveNormal priority; Windows and Linux may schedule the threads differently. section 7.6



