如何模拟c#线程饥饿
本文关键字:线程 饥饿 模拟 何模拟 | 更新日期: 2023-09-27 18:17:16
我正在尝试诱导/引起线程饥饿,以便观察c#中的效果。
谁能建议一个(简单的)应用程序,可以创建,以诱导线程饥饿?
设置线程优先级和线程亲和性
工人类
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,如果你有多核系统,你可能需要设置线程关联。您可能还需要创建更多的线程来查看真正的饥饿。
在任务管理器中为应用程序设置线程关联,以便它只在一个核心上运行。然后在应用程序中启动一个高优先级的繁忙线程。