【发布时间】:2016-06-07 12:42:31
【问题描述】:
我试图了解 CPU 如何在具有不同线程数的不同进程之间分配。我有两个程序 Program1 和 Program2。
Program1 有 5 个线程,而 Program2 只有主线程。
场景-1:
terminal-1 : ./Program1
terminal-2 : ./Program2
当我在一个终端运行 Program1 并在另一个终端运行 Program2 时,CPU 分配完成了 Program1 的 50% 和 Program2 的 50%。 Program1 的每个线程获得 10%(Program1 累计 50%)
这表明,无论一个进程有多少线程,每个进程都将获得相同的 CPU 份额。 这表明 CPU 分配是在进程级别完成的。
pstree 展示
├─bash───P1───5*[{P1}]
├─bash───P2───{P2}
场景-2:
terminal-1 : ./Program1 & ./Program2
当我在 SAME 终端中同时运行 Program1 和 Program2 时,Program1 和 Program2 的所有线程的 CPU 分配是相等的。这意味着 Program1 的每个线程都获得了将近 17%(累计 Program1 获得了 83%), Program2 也获得了 17%。 这表明 CPU 分配是在线程级别完成的。
pstree 展示
├─bash─┬─P1───5*[{P1}]
│ └─P2
我使用的是 Ubuntu 12.04.4 LTS,内核 - config-3.11.0-15-generic。我也用过 Ubuntu 14.04.4 , kernel-3.16.x 并得到了类似的结果。
谁能解释一下LINUX KERNEL的CPU调度器如何区分SCENARIO-1和SCENARIO-2?
我认为 CPU 调度程序在分配 CPU 之前会在某处区分两种 SCENARIO。
为了了解 CPU 调度程序如何区分 SCENARIO-1 和 SCENARIO-2,我下载了 Linux 内核源代码。
但是,我没有在源代码中找到区分 SCENARIO-1 和 SCENARIO-2 的地方.
如果有人指出 CPU 调度程序区分 SCENARIO-1 和 SCENARIO-2 的源代码或函数,那就太好了。
提前致谢。
注意:虽然 Ubuntu 是基于 Debian,但令人惊讶的是,在 Debian 8 (kernel-3.16.0-4-686-pae) 中 SCENARIO 的 CPU 分配都是在线程级别完成的 意味着每个线程的 Program1 获得了近 17%(累计 Program1 获得了 83%), Program2 也获得了 17%。
这里是代码: Program1(5线程)
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
// Let us create a global variable to change it in threads
int g = 0;
// The function to be executed by all threads
void *myThreadFun(void *vargp)
{
// Store the value argument passed to this thread
int myid = (int)vargp;
// Let us create a static variable to observe its changes
static int s = 0;
// Change static and global variables
++s; ++g;
// Print the argument, static and global variables
printf("Thread ID: %d, Static: %d, Global: %d\n", myid, ++s, ++g);
while(1); // Representing CPU Bound Work
}
int main()
{
int i;
pthread_t tid[5];
// Let us create three threads
for (i = 0; i < 5; i++)
pthread_create(&tid[i], NULL, myThreadFun, (void *)i);
for (i = 0; i < 5; i++)
pthread_join(tid[i],NULL);
return 0;
}
Program2(只有主线程)
#include <stdio.h>
#include <stdlib.h>
int main()
{
while(1);// Representing CPU Bound Work
}
为了禁用 gcc 的所有优化,我在编译这两个程序时都使用了 O0 选项。
gcc -O0 program1.c -o p1 -lpthread
gcc -O0 program2.c -o p2
更新:根据 ninjalj 的解释,在场景 1 中,CPU 分配是在控制组级别完成的,因为我使用两个不同的终端(意味着两个不同的会话),因此有 2 个不同的控制组和每个控制组获得 50% 的 CPU 分配。这是由于某种原因,默认情况下启用了自动分组。
由于 Program2 只有一个线程,而 Program1 有更多线程,我想运行 在单独的终端(不同的会话)中的程序和为 Program1 获得更多的 CPU 分配(如在场景 2 中,Program1 获得 83% 的 CPU 分配,而 Program2 为 17%)。在任何情况下,Scenario1 的 CPU 分配是否可能与 Ubuntu 中的 Scenario-2 相同?
虽然 Ubuntu 基于 Debian,但令我感到惊讶的是,Debian 和 Ubuntu 的行为仍然不同。在 Debian 的情况下,Program1 在两个场景中都获得了更多的 CPU。
【问题讨论】:
-
"这说明,不管一个进程有多少线程,每个进程都会得到同等份额的CPU。这说明CPU分配是在进程级别完成的。" 废话.它没有显示这样的东西。
-
我非常有信心调度算法记录在某处。至少有源代码。
-
@DavidSchwartz,实验结果表明,在 Scenario-1 中,每个进程都获得了相等的 CPU 份额。我不明白你为什么说“它没有显示这样的事情”?能详细点吗?
-
Understanding renice的可能重复
-
实验 1 没有“[show] CPU 分配在进程级别完成”。在这种情况下,它实际上是在控制组级别完成的,并且在每个控制组内部,它都是在线程级别完成的。
标签: c linux multithreading performance linux-kernel