如何设置特定 pthread 的 CPU 亲和性? [英] how to set CPU affinity of a particular pthread?
问题描述
我想指定特定 pthread 的 cpu-affinity.到目前为止,我发现的所有参考资料都涉及设置进程 (pid_t) 而非线程 (pthread_t) 的 CPU 亲和性.我尝试了一些传递 pthread_t 的实验,但正如预期的那样失败了.我是在尝试做一些不可能的事情吗?如果没有,请你发个指针好吗?感谢一百万.
I'd like to specify the cpu-affinity of a particular pthread. All the references I've found so far deal with setting the cpu-affinity of a process (pid_t) not a thread (pthread_t). I tried some experiments passing pthread_t's around and as expected they fail. Am I trying to do something impossible? If not, can you send a pointer please? Thanks a million.
推荐答案
这是我为让生活更轻松而制作的包装器.它的作用是调用线程卡住"到具有 id core_id
的核心:
This is a wrapper I've made to make my life easier. Its effect is that the calling thread gets "stuck" to the core with id core_id
:
// core_id = 0, 1, ... n-1, where n is the system's number of cores
int stick_this_thread_to_core(int core_id) {
int num_cores = sysconf(_SC_NPROCESSORS_ONLN);
if (core_id < 0 || core_id >= num_cores)
return EINVAL;
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(core_id, &cpuset);
pthread_t current_thread = pthread_self();
return pthread_setaffinity_np(current_thread, sizeof(cpu_set_t), &cpuset);
}
这篇关于如何设置特定 pthread 的 CPU 亲和性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!