我搜索有关CPU亲和力的问题/答案,并读取结果,但我仍然不能让我的线程固定到一个CPU。
我正在开发一个将在专用linux盒上运行的应用程序,所以我不关心其他进程,只关心我自己的进程。此应用程序当前生成一个p线程,然后主线程进入一个while循环,使用POSIX msg队列处理控制消息。这个while循环阻塞等待控件msg进入并处理它。所以主线程是非常简单的,不重要的。我的代码工作得很好,因为我可以发送这个应用程序的消息,它将处理它们很好。所有控制消息的大小都非常小,只用于控制应用程序的功能,也就是说,只有少数控制消息被发送/接收。
在输入这个while循环之前,我使用sched_getaffinity()记录所有可用的CPU。然后,我使用sched_setaffinity()将这个进程设置为单个CPU。然后再次调用sched_getaffinity()来检查它是否设置为只在一个CPU上运行,并且它确实是正确的。
所产生的单个线程也做了类似的事情。我在新创建的线程中做的第一件事是调用pthread_getaffinity_np()并检查可用的CPU,然后调用pthread_setaffinity_np()将其设置为不同的CPU,然后调用pthread_getaffinity_np()来检查是否按需要设置它,并且它确实是正确的。
这就是令人困惑的地方。当我运行该应用程序并在系统监视器中查看CPU历史记录时,我发现与我在没有所有这些设置关联的情况下运行该应用程序时没有什么不同。调度程序仍然在这个四核盒上的4个CPU中运行几秒钟。因此,调度程序似乎忽略了我的关联设置。
我是否错误地期望看到主线程和线程在它们自己的单个CPU中运行的一些证据??还是我忘了做更多的事情来让这件事按我的意愿运作?
谢谢,
-Andres
发布于 2013-12-14 03:22:35
你没有答案,我会尽我所能给你一些帮助。
假设您检查了来自pthread_setaffinity_np的返回值:
如何分配您的cpuset是非常重要的,创建它的主线程。为了你想要的。它将传播到连续线程。你查过退货码了吗?
您实际得到的cpuset将是硬件可用cpus和您定义的cpuset的交集。下面的代码中的min.h是一个通用的构建包含文件。您必须定义_GNU_SOURCE --请注意comment on the last line of the code.、CPUSET和CPUSETSIZE是宏。我想我把它们定义在别的地方,我不记得了。它们可能在一个标准的标题中。
#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;
}https://stackoverflow.com/questions/20535789
复制相似问题