Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 416
Dot NET Avatar asked Dec 09 '11 20:12

Dot NET


People also ask

How do you simulate C code?

By default no C code will be simulated until the C Simulation button is enabled. C Code icons will simply be skipped by the simulator. The C Simulation button can be found on the main toolbar and via the DEBUG menu. C Simulation is enabled when the button icon is highlighted by a bounding square.

What is Simulation in C?

A simulation is a computer model that mimics the operation of a real or proposed system and it is time based and takes into account all the resources and constraints involved.

Is C++ good for simulations?

If you are looking for mathematical modeling and analysis, then Python and Matlab are good options. If you want to work with large data (CFD modelling), then C++ and Fortran are preferred languages.


2 Answers

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.

like image 101
oleksii Avatar answered Sep 27 '22 16:09

oleksii


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.

like image 21
Guffa Avatar answered Sep 27 '22 17:09

Guffa