gpt4 book ai didi

c# - 如何模拟C#线程饥饿

转载 作者:可可西里 更新时间:2023-11-01 07:45:57 24 4
gpt4 key购买 nike

我正在尝试引发/导致线程饥饿,以便观察 C# 中的影响。

任何人都可以建议一个(简单的)应用程序,该应用程序可以创建以引起线程饥饿吗?

最佳答案

设置线程优先级和线程亲和度

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

并测试

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

代码主要取自 msdn另外,如果你有多核系统,你可能需要设置 thread affinity .您可能还需要创建更多线程才能看到真正的饥饿。

关于c# - 如何模拟C#线程饥饿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8451105/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com