Dot NET
Dot NET

Reputation: 4897

How to simulate C# thread starvation

I'm trying to induce/cause thread starvation so as to observe the effects in C#.

Can anyone kindly suggest a (simple) application which can be created so as to induce thread starvation?

Upvotes: 15

Views: 4217

Answers (2)

oleksii
oleksii

Reputation: 35905

Set thread priority and thread affinity

Worker class

class PriorityTest
{
    volatile bool loopSwitch;
    public PriorityTest()
    {
        loopSwitch = true;
    }

    public bool LoopSwitch
    {
        set { loopSwitch = value; }
    }

    public void ThreadMethod()
    {
        long threadCount = 0;

        while (loopSwitch)
        {
            threadCount++;
        }
        Console.WriteLine("{0} with {1,11} priority " +
            "has a count = {2,13}", Thread.CurrentThread.Name,
            Thread.CurrentThread.Priority.ToString(),
            threadCount.ToString("N0"));
    }
}

And test

class Program
{

    static void Main(string[] args)
    {
        PriorityTest priorityTest = new PriorityTest();
        ThreadStart startDelegate =
            new ThreadStart(priorityTest.ThreadMethod);

        Thread threadOne = new Thread(startDelegate);
        threadOne.Name = "ThreadOne";
        Thread threadTwo = new Thread(startDelegate);
        threadTwo.Name = "ThreadTwo";

        threadTwo.Priority = ThreadPriority.Highest;
        threadOne.Priority = ThreadPriority.Lowest;
        threadOne.Start();
        threadTwo.Start();

        // Allow counting for 10 seconds.
        Thread.Sleep(10000);
        priorityTest.LoopSwitch = false;

        Console.Read();
    }
}

Code mostly taken from msdn also if you have multicore system you may need to set thread affinity. You may also need to create more threads to see real starvation.

Upvotes: 12

Guffa
Guffa

Reputation: 700322

Set the thread affinity for your application in the task manager so that it only runs on one core. Then start a busy thread in your application with a high priority.

Upvotes: 3

Related Questions