我的代码似乎没有按照我想要的方式工作,我试图找到问题所在,但我似乎无法看到它有什么问题......我想我可能已经理解了整件事都错了。 我试图设置一个线程的亲和力,我想让它在特定的cpu上运行,然后当我运行它并显示sched_getcpu()的值时,它不是正确的值,而不是我强迫我的线程运行的cpu上。
#define _GNU_SOURCE
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sched.h>
#include <sys/wait.h>
void *fonction(void *arg){
int n=(int)arg;
int res=1;
int i;
for(i=2;i<=n;i++) res=res*i;
fprintf(stderr,"calculating %d! by cpu %d\n",n,sched_getcpu());
sleep(5);
return (void*)res;
}
int main(int argc, char *argv[]){
pthread_t *threads=NULL;
cpu_set_t cpuset;
void *retour;
pthread_attr_t attr;
int cpu;
int ar;
int val;
int numcpu=sysconf(_SC_NPROCESSORS_ONLN);
if(sscanf(argv[1],"%d",&ar)!=1){
fprintf(stderr,"error\n");
exit(EXIT_FAILURE);
}
threads=calloc(numcpu,sizeof(pthread_t));
if(threads==NULL){
fprintf(stderr,"calloc error\n");
exit(EXIT_FAILURE);
}
for(cpu=0;cpu<numcpu;cpu++){
val=ar-cpu;
pthread_attr_init(&attr);
CPU_ZERO(&cpuset);
CPU_SET(cpu,&cpuset);
if(pthread_create(&threads[cpu],&attr,fonction,(void*)val)!=0){
fprintf(stderr,"problem creating thread\n");
exit(EXIT_FAILURE);
}
if(pthread_attr_setaffinity_np(&attr,sizeof(cpu_set_t),&cpuset)!=0){
fprintf(stderr,"error setting affinity\n");
exit(EXIT_FAILURE);
}
pthread_join(threads[cpu],&retour);
fprintf(stderr,"%d!=%d done by %d\n",val,(int)retour,cpu);
}
free(threads);
pthread_exit(NULL);
return 0;
}
执行给出 this