Dot*_*NET 15 .net c# multithreading
我试图诱导/导致线程饥饿,以便观察C#中的效果.
任何人都可以建议一个(简单的)应用程序,可以创建,以引起线程饥饿?
ole*_*sii 13
设置线程优先级和线程关联
工人阶级
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"));
}
}
Run Code Online (Sandbox Code Playgroud)
并测试
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();
}
}
Run Code Online (Sandbox Code Playgroud)
代码主要来自msdn,如果你有多核系统,你可能需要设置线程亲和力.您可能还需要创建更多线程才能看到真正的饥饿.