c - linux 中的 sched_setaffinity cpu 亲和性

标签 c linux cpu

我在一台有 1 个插槽、4 个内核的服务器上用 Linux 做了一个 sched_setaffinity 测试, 以下/proc/cpuinfo 显示 cpu 信息:

processor       : 0
model name      : Intel(R) Core(TM)2 Quad CPU    Q8400  @ 2.66GHz
cache size      : 2048 KB
physical id     : 0
siblings        : 4
cpu cores       : 4

processor       : 1
model name      : Intel(R) Core(TM)2 Quad CPU    Q8400  @ 2.66GHz
cache size      : 2048 KB
physical id     : 0
siblings        : 4
cpu cores       : 4

processor       : 2
model name      : Intel(R) Core(TM)2 Quad CPU    Q8400  @ 2.66GHz
cache size      : 2048 KB
physical id     : 0
siblings        : 4
cpu cores       : 4

processor       : 3
model name      : Intel(R) Core(TM)2 Quad CPU    Q8400  @ 2.66GHz
cache size      : 2048 KB
physical id     : 0
siblings        : 4
cpu cores       : 4

我有一个简单的测试应用程序:

struct foo {
    int x;
    int y;
}  ;

//globar var
volatile struct foo fvar ;

pid_t gettid( void )
{
    return syscall( __NR_gettid );
}

void *test_func0(void *arg)
{
    int proc_num = (int)(long)arg;
    cpu_set_t set;

    CPU_ZERO( &set );
    CPU_SET( proc_num, &set );
    printf("proc_num=(%d)\n",proc_num) ;
    if (sched_setaffinity( gettid(), sizeof( cpu_set_t ), &set ))
    {
        perror( "sched_setaffinity" );
        return NULL;
    }


    int i=0;
    for(i=0;i<1000000000;++i){
        __sync_fetch_and_add(&fvar.x,1);
    }
    return NULL;
} //test_func0

编译: gcc testsync.c -D_GNU_SOURCE -lpthread -o testsync.exe 以下是测试结果:

2 threads running test_func0 in core 0,1  take 35 secs ;
2 threads running test_func0 in core 0,2  take 55 secs ;
2 threads running test_func0 in core 0,3  take 55 secs ;
2 threads running test_func0 in core 1,2  take 55 secs ;
2 threads running test_func0 in core 1,3  take 55 secs ;
2 threads running test_func0 in core 2,3  take 35 secs ;

我想知道为什么在核心 (0,1) 或核心 (2,3) 中运行的 2 个线程会很多 别人更快?如果我在同一个核心运行 2 个线程,比如 core(1,1) , core(2,2),core(3,3) ,这需要 28 秒,也很困惑为什么会这样?

最佳答案

核心 0 和 1 共享一个 L2 缓存,核心 2 和 3 也是如此。在共享缓存的两个核心上运行使得共享变量保留在 L2 缓存中,这使得速度更快。

在当今的 Intel 处理器中,情况并非如此,其中 L2 按内核计算。但是在您使用的 CPU 上,它是这样工作的(它实际上是通过将两个双核 CPU 粘合在一起制成的四核 CPU)。

关于c - linux 中的 sched_setaffinity cpu 亲和性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14392656/

相关文章:

c - freopen() 和流的奇怪行为

c - 如何在 C 中为密码的每个输入字符显示 * - 使字符不可见

c - 如何在 C 中制作一个简单的计算器来保存中间结果

c - 访问不同 c 文件中 pthread 中的全局变量

c - 链接到静态库的多个版本

asp.net - 尝试在 Apache Mono 上托管 .net Web 应用程序

c - 原始套接字发送的 ARP 回复被忽略

linux-kernel - 什么是 CPU 内核/特权模式,操作系统如何保护它?

c++ - 限制 CPU 速度以进行分析

c - 测量矩阵乘法参数的程序错误