我有線程親和力的奇怪問題。我在C創建一個程序:Android與C程序中的線程親和力
#define _GNU_SOURCE
#include<stdio.h>
#include <sys/syscall.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
#include <time.h>
#include <errno.h>
#define handle_error_en(en, msg) \
do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)
#define NANOS 1000000000LL
#define SIZE 1000
void* mesaureTime(void *cpu)
{
unsigned long i = 0;
int s;
cpu_set_t cpuset;
struct timespec start, end;
long elapsed;
pthread_t id = pthread_self();
CPU_ZERO(&cpuset);
CPU_SET(*(int *) cpu, &cpuset);
s = pthread_setaffinity_np(id, sizeof(cpu_set_t), &cpuset);
if (s != 0)
handle_error_en(s, "pthread_setaffinity_np");
if(pthread_equal(id,tid[0]))
printf("Realizando test...\n");
while(i<SIZE){
clock_gettime(CLOCK_MONOTONIC, &start);
// Do some calculation.
factorial(150000);
clock_gettime(CLOCK_MONOTONIC, &end);
arrayTimes[i] = elapsed;
elapsed = end.tv_nsec - start.tv_nsec + (end.tv_sec - start.tv_sec)*NANOS;
i++;
}
printf("Finished\n");
return 0;
}
int factorial(int a){
if (a==1){
return 1;
}else{
a=a*factorial(a-1);
}
return a;
}
int main(int argc, char *argv[])
{
int i = 0;
int err, result;
int *cpu_pointer;
int cpu = atoi(argv[1]);
cpu_pointer = &cpu;
err = pthread_create(&tid[i], NULL, mesaureTime, (void *) cpu_pointer);
if (err != 0)
printf("can't create thread :[%s]", strerror(err));
else
printf("Hilo de test creado satisfactoriamente\n");
pthread_join(tid[0], NULL);
printf("\n Finalizado el test\n");
return 0;
}
此代碼的工作以及雙核英特爾CPU與Ubuntu的,但是當我已經與ARM-Linux的gnueabi-GCC編譯它,我在我的Android設備已經執行(Nexus 4,Nexus 5和S4)中,程序無法分配CPU 2,CPU 3或CPU 4中的線程,它只能在CPU 1中工作。pthread_setaffinity_np函數始終返回CPU 2的錯誤(無效參數) ,3或4.
我在這裏讀到了一些問題Is it possible to set affinity with sched_setaffinity in Android?和Android set thread affinity。我已經嘗試過,但我已經獲得了相同的結果。
您的內核很可能不允許用戶空間程序修改親和性。在這種情況下,您將需要驅動程序從您的進程中刪除「PF_NO_SETAFFINITY」標誌。 –
感謝您的回答。我如何在我的過程中做到這一點? – avarana