如何设置特定pthread的CPU亲和力?

我想指定特定pthread的cpu亲和力。到目前为止,我发现的所有引用都涉及设置进程(pid_t)而不是线程(pthread_t)的cpu亲和力。我尝试了一些传递pthread_t的实验,并且按预期它们会失败。我是否在尝试做一些不可能的事情?如果没有,您可以发送指针吗?太感谢了。



繁星coding
浏览 946回答 3
3回答

哈士奇WWW

这是我为了使生活更轻松而制作的包装纸。它的作用是使调用线程被“塞住”到具有id的内核core_id:// core_id = 0, 1, ... n-1, where n is the system's number of coresint stick_this_thread_to_core(int core_id) {&nbsp; &nbsp;int num_cores = sysconf(_SC_NPROCESSORS_ONLN);&nbsp; &nbsp;if (core_id < 0 || core_id >= num_cores)&nbsp; &nbsp; &nbsp; return EINVAL;&nbsp; &nbsp;cpu_set_t cpuset;&nbsp; &nbsp;CPU_ZERO(&cpuset);&nbsp; &nbsp;CPU_SET(core_id, &cpuset);&nbsp; &nbsp;pthread_t current_thread = pthread_self();&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;return pthread_setaffinity_np(current_thread, sizeof(cpu_set_t), &cpuset);}

慕容3067478

假设Linux:设置相似性的界面是-您可能已经发现:int sched_setaffinity(pid_t pid,size_t cpusetsize,cpu_set_t *mask);传递0作为pid,它将仅适用于当前线程,或者让其他线程通过linux特定的调用报告其内核pid pid_t gettid(void);并将其作为pid传递。引用手册页亲和力掩码实际上是每个线程的属性,可以针对线程组中的每个线程分别进行调整。调用gettid(2)返回的值可以在pid参数中传递。将pid指定为0将为调用线程设置属性,并将从调用返回的值传递给getpid(2)将为线程组的主线程设置属性。(如果使用的是POSIX线程API,请使用pthread_setaffinity_np(3)而不是sched_setaffinity()。)

倚天杖

//compilation: gcc -o affinity affinity.c -lpthread#define _GNU_SOURCE#include <sched.h>&nbsp; &nbsp;//cpu_set_t , CPU_SET#include <pthread.h> //pthread_t#include <stdio.h>void *th_func(void * arg);&nbsp;int main(void) {&nbsp; pthread_t thread; //the thread&nbsp; pthread_create(&thread,NULL,th_func,NULL);&nbsp;&nbsp; pthread_join(thread,NULL);&nbsp; &nbsp;&nbsp; return 0;}void *th_func(void * arg){&nbsp;&nbsp;&nbsp; //we can set one or more bits here, each one representing a single CPU&nbsp; cpu_set_t cpuset;&nbsp;&nbsp; //the CPU we whant to use&nbsp; int cpu = 2;&nbsp; CPU_ZERO(&cpuset);&nbsp; &nbsp; &nbsp; &nbsp;//clears the cpuset&nbsp; CPU_SET( cpu , &cpuset); //set CPU 2 on cpuset&nbsp; /*&nbsp; &nbsp;* cpu affinity for the calling thread&nbsp;&nbsp; &nbsp;* first parameter is the pid, 0 = calling thread&nbsp; &nbsp;* second parameter is the size of your cpuset&nbsp; &nbsp;* third param is the cpuset in which your thread will be&nbsp; &nbsp;* placed. Each bit represents a CPU&nbsp; &nbsp;*/&nbsp; sched_setaffinity(0, sizeof(cpuset), &cpuset);&nbsp; while (1);&nbsp; &nbsp; &nbsp; &nbsp;; //burns the CPU 2&nbsp; return 0;}在POSIX环境中,可以使用cpusets来控制进程或pthread可以使用哪些CPU。这种类型的控制称为CPU关联。函数“ sched_setaffinity”接收pthread ID和cpuset作为参数。当您在第一个参数中使用0时,调用线程将受到影响
打开App,查看更多内容
随时随地看视频慕课网APP