如何模拟C#线程匮乏 [英] How to simulate C# thread starvation

查看:177
本文介绍了如何模拟C#线程匮乏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图诱使/事业线程不足,以观察在C#中的作用。

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?

推荐答案

设置线程优先级和线程关联

Set thread priority and thread affinity

Worker类

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"));
    }
}

和测试

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主要来自 MSDN 此外,如果你有多核系统,您可能需要设置<一个href="http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/a55733db-cac0-4ccb-a3cc-a584742b41f9/">thread亲和力。您可能还需要创建多个线程,看看真正的饥饿。

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.

这篇关于如何模拟C#线程匮乏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆