【发布时间】:2012-02-17 14:53:06
【问题描述】:
我有一个简单的程序,它启动 n 个线程并在每个线程上创建一些负载。 如果我只启动一个线程,一个核心会获得大约 100% 的负载。 如果我用 16 个线程启动一个进程(这意味着每个内核一个线程),我只会得到大约 80% 的负载。 如果我用 2 个线程启动 8 个进程(这仍然意味着每个内核一个线程),我会得到大约 99% 的负载。 我在这个示例中没有使用任何锁定。
这种行为的原因是什么? 我知道如果有 100 个线程在工作,负载就会下降,因为操作系统必须安排很多。 但在这种情况下,线程数只有内核数。
情况更糟(至少对我来说)。 如果我在循环中添加一个简单的 thread.sleep(0),一个进程和 16 个线程的负载将增加高达 95%。
任何人都可以回答这个问题,或提供有关此特定主题的更多信息的链接吗?
//Sample application which reads the number of threads to be started from Console.ReadLine
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the number of threads to be started");
int numberOfThreadsToStart;
string input = Console.ReadLine();
int.TryParse(input, out numberOfThreadsToStart);
if(numberOfThreadsToStart < 1)
{
Console.WriteLine("No valid number of threads entered. Exit now");
Thread.Sleep(1500);
return;
}
List<Thread> threadList = new List<Thread>();
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < numberOfThreadsToStart; i++)
{
Thread workerThread = new Thread(MakeSomeLoad);
workerThread.Start();
threadList.Add(workerThread);
}
while (true)
{
Console.WriteLine("I'm spinning... ");
Thread.Sleep(2000);
}
}
static void MakeSomeLoad()
{
for (int i = 0; i < 100000000; i++)
{
for (int j = 0; j < i; j++)
{
//uncomment the following line to increase the load
//Thread.Sleep(0);
StringBuilder sb = new StringBuilder();
sb.Append("hello world" + j);
}
}
}
}
【问题讨论】:
标签: c# multithreading