【发布时间】:2018-11-15 23:18:11
【问题描述】:
根据 docs.microsoft.com [1、2、3、4]:
只有在执行的前台线程数小于处理器数时,才会执行后台线程。
但是,如果我在 4 核 CPU(没有超线程)上启动 4 个前台线程,然后启动 4 个后台线程,则前台线程和后台线程将并行运行,这似乎与陈述相矛盾以上。
代码示例:
static void Main(string[] args)
{
int numberOfProcessors = 4;
for (int i = 0; i < numberOfProcessors; i++)
{
int threadNumber = i;
new Thread(() =>
{
Console.WriteLine($"Foreground thread {threadNumber} started.");
for (int j = 1; j <= 100; j++)
{
for (long k = 0; k < 10000000000; k++);
Console.WriteLine($"Foreground thread {threadNumber} progress: {j}%.");
}
})
.Start();
}
for (int i = 0; i < numberOfProcessors; i++)
{
int threadNumber = i;
var backgroundThread = new Thread(() =>
{
Console.WriteLine($"Background thread {threadNumber} started.");
for (int j = 1; j <= 100; j++)
{
for (long k = 0; k < 10000000000; k++);
Console.WriteLine($"Background thread {threadNumber} progress: {j}%.");
}
});
backgroundThread.IsBackground = true;
backgroundThread.Start();
}
Console.ReadLine();
}
输出:
Foreground thread 1 started.
Foreground thread 0 started.
Foreground thread 3 started.
Foreground thread 2 started.
Background thread 0 started.
Background thread 1 started.
Background thread 2 started.
Background thread 3 started.
Foreground thread 2 progress: 1%.
Foreground thread 0 progress: 1%.
Foreground thread 1 progress: 1%.
Foreground thread 3 progress: 1%.
Background thread 1 progress: 1%.
Background thread 0 progress: 1%.
Background thread 2 progress: 1%.
Background thread 3 progress: 1%.
Foreground thread 0 progress: 2%.
Foreground thread 2 progress: 2%.
Foreground thread 1 progress: 2%.
Foreground thread 3 progress: 2%.
Background thread 0 progress: 2%.
Background thread 1 progress: 2%.
Background thread 3 progress: 2%.
Background thread 2 progress: 2%.
Foreground thread 0 progress: 3%.
Foreground thread 2 progress: 3%.
Foreground thread 1 progress: 3%.
Foreground thread 3 progress: 3%.
Background thread 1 progress: 3%.
Background thread 0 progress: 3%.
Background thread 3 progress: 3%.
Background thread 2 progress: 3%.
...
这个陈述是错误的还是我完全理解错了?
【问题讨论】:
-
MSDN 文档完全是错误的。它没有给出“前台”与“后台”线程的定义。就操作系统而言,前台线程是具有用户正在与之交互的窗口的线程。它确实获得了更大的线程量。
-
这会是带有超线程的 4 核 Intel 吗?这将在这 4 个内核上为您提供 8 个线程。也许用 8 而不是 4 再试一次...
-
@Patrick Hughes,没有超线程,编辑了问题,谢谢。
标签: c# .net multithreading clr