【问题标题】:why doesn't the System Monitor show correct CPU affinity?为什么系统监视器不显示正确的 CPU 关联性?
【发布时间】:2013-12-30 09:48:52
【问题描述】:

我已经搜索了有关 CPU 亲和性的问题/答案并阅读了结果,但我仍然无法让我的线程确定单个 CPU。

我正在开发一个将在专用 linux 机器上运行的应用程序,因此我不关心其他进程,只关心我自己的进程。此应用程序当前产生一个 pthread,然后主线程进入一个 while 循环,以使用 POSIX msg 队列处理控制消息。这个while循环阻塞等待控制消息进入然后处理它。所以主线程非常简单且非关键。我的代码运行良好,因为我可以发送这个应用程序消息,它会很好地处理它们。所有控制消息的大小都非常小,仅用于控制应用程序的功能,也就是说,只有少数控制消息被发送/接收。

在进入这个 while 循环之前,我使用 sched_getaffinity() 来记录所有可用的 CPU。然后我使用 sched_setaffinity() 将此进程设置为单个 CPU。然后我再次调用 sched_getaffinity() 来检查它是否设置为仅在一个 CPU 上运行并且确实正确。

生成的单个 pthread 执行类似的操作。我在新创建的 pthread 中做的第一件事是调用 pthread_getaffinity_np() 并检查可用的 CPU,然后调用 pthread_setaffinity_np() 将其设置为不同的 CPU,然后调用 pthread_getaffinity_np() 以检查它是否按需要设置并且确实如此正确。

这是令人困惑的。当我运行应用程序并在系统监视器中查看 CPU 历史记录时,我发现与运行应用程序时没有所有这些设置的关联性内容没有区别。调度程序仍然在这个四核机器上的 4 个 CPU 中的每一个中运行几秒钟。因此,调度程序似乎忽略了我的亲和力设置。

我期望看到一些证据证明主线程和 pthread 实际上是在它们自己的单个 CPU 中运行,我错了吗?还是我忘了做更多的事情来让它按我的意图工作?

谢谢,

-安德烈斯

【问题讨论】:

    标签: linux multithreading pthreads


    【解决方案1】:

    你没有答案,我会尽我所能:一些部分帮助

    假设您检查了 pthread_setaffinity_np 的返回值:

    你如何分配你的cpuset非常重要,在主线程中创建它。为了你想要的。它将传播到后续线程。你检查返回码了吗?

    您实际获得的 cpuset 将是硬件可用 cpus 和您定义的 cpuset 的交集。 下面代码中的min.h 是一个通用的构建包含文件。您必须定义 _GNU_SOURCE - 请注意 comment on the last line of the code. CPUSETCPUSETSIZE 是宏。我想我在其他地方定义了它们,我不记得了。它们可能在标准标题中。

    #define _GNU_SOURCE
    #include "min.h"
    #include <pthread.h>
    
    
    int
    main(int argc, char **argv)
    {
        int s, j;
        cpu_set_t cpuset;
        pthread_t tid=pthread_self();
    
        // Set affinity mask to include CPUs 0 & 1
    
        CPU_ZERO(&cpuset);
        for (j = 0; j < 2; j++)
            CPU_SET(j, &cpuset);
    
        s = pthread_setaffinity_np(tid, sizeof(cpu_set_t), &cpuset);
        if (s != 0)
        {
            fprintf(stderr, "%d ", s);
            perror(" pthread_setaffinity_np");
            exit(1);
         }
         // lets see what we really have in the actual affinity mask assigned our thread
    
        s = pthread_getaffinity_np(tid, sizeof(cpu_set_t), &cpuset);
        if (s != 0)
        {
            fprintf(stderr, "%d ", s);
            perror(" pthread_setaffinity_np");
            exit(1);
         }
    
        printf("my cpuset has:\n");
        for (j = 0; j < CPU_SETSIZE; j++)
            if (CPU_ISSET(j, &cpuset))
                printf("    CPU %d\n", j);
        // @Andres note: any pthread_create call from here on creates a thread with the identical
        // cpuset - you do not have to call it in every thread.
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      • 2012-05-13
      相关资源
      最近更新 更多