問題描述
假設我運行一個簡單的單線程進程,如下所示:
Say I run a simple single-threaded process like the one below:
public class SirCountALot {
public static void main(String[] args) {
int count = 0;
while (true) {
count++;
}
}
}
(這是 Java,因為這是我熟悉的,但我懷疑這并不重要)
(This is Java because that's what I'm familiar with, but I suspect it doesn't really matter)
我有一個 i7 處理器(4 核,或 8 個計數超線程),我運行的是 64 位 Windows 7,所以我啟動了 Sysinternals Process Explorer 來查看 CPU 使用情況,正如預期的那樣,我看到它正在使用大約 20% 的可用 CPU.
I have an i7 processor (4 cores, or 8 counting hyperthreading), and I'm running Windows 7 64-bit so I fired up Sysinternals Process Explorer to look at the CPU usage, and as expected I see it is using around 20% of all available CPU.
但是當我切換為每個 CPU 顯示 1 個圖表的選項時,我看到 CPU 使用率分布在所有核心上,而不是使用 4 個核心"中的 1 個:
But when I toggle the option to show 1 graph per CPU, I see that instead of 1 of the 4 "cores" being used, the CPU usage is spread all over the cores:
相反,我期望的是 1 個核心最大化,但這僅在我將進程的親和性設置為單個核心時才會發生.
Instead what I would expect is 1 core maxed out, but this only happens when I set the affinity for the process to a single core.
為什么工作負載會分散到不同的核心上?將工作負載分配到多個內核上會不會影響緩存或導致其他性能損失?
Why is the workload split over the separate cores? Wouldn't splitting the workload over several cores mess with the caching or incur other performance penalties?
僅僅是為了防止一個核心過熱嗎?還是有更深層次的原因?
Is it for the simple reason of preventing overheating of one core? Or is there some deeper reason?
我知道操作系統負責調度,但我想知道它為什么麻煩".當然,從幼稚的角度來看,將(大部分*)單線程進程固定到 1 個內核是更簡單的 &更高效的方式?
I'm aware that the operating system is responsible for the scheduling, but I want to know why it "bothers". Surely from a naive viewpoint, sticking a (mostly*) single-threaded process to 1 core is the simpler & more efficient way to go?
*我說主要是單線程,因為這里有多個線程,但其中只有 2 個在做任何事情:
*I say mostly single-threaded because there's multiple theads here, but only 2 of them are doing anything:
推薦答案
操作系統負責調度.可以自由地停止一個線程并在另一個 CPU 上重新啟動它.即使機器沒有做任何其他事情,它也會這樣做.
The OS is responsible for scheduling. It is free to stop a thread and start it again on another CPU. It will do this even if there is nothing else the machine is doing.
進程在 CPU 周圍移動,因為操作系統不認為有任何理由每次都在同一個 CPU 上繼續運行線程.
The process is moved around the CPUs because the OS doesn't assume there is any reason to continue running the thread on the same CPU each time.
出于這個原因,我編寫了一個用于將線程鎖定到 CPU 的庫,這樣它就不會四處移動,也不會被其他線程中斷.這減少了延遲并提高了吞吐量,但確實會占用該線程的 CPU.這適用于 Linux,也許您可??以將其調整為適用于 Windows.https://github.com/peter-lawrey/Java-Thread-Affinity/wiki/入門
For this reason I have written a library for lock threads to a CPU so it won't move around and won't be interrupted by other threads. This reduces latency and improve throughput but does tire up a CPU for that thread. This works for Linux, perhaps you can adapt it for Windows. https://github.com/peter-lawrey/Java-Thread-Affinity/wiki/Getting-started
這篇關于為什么單線程進程在多個處理器/內核上執行?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!