Skip to content

Instantly share code, notes, and snippets.

@YuMS
Last active May 31, 2022 16:15
Show Gist options
  • Save YuMS/1e70dcf5e01b5acbaac8d04a2ee00346 to your computer and use it in GitHub Desktop.
Save YuMS/1e70dcf5e01b5acbaac8d04a2ee00346 to your computer and use it in GitHub Desktop.
Should work on armv7 as well as armv8
#include <sys/syscall.h>
#include <sys/types.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>
#include <cstdio>
#ifndef CPU_SETSIZE
#define CPU_SETSIZE 1024
#define __NCPUBITS (8 * sizeof (unsigned long))
#ifdef __ANDROID__
#define gettid() syscall(__NR_gettid)
#else
#define gettid() syscall(SYS_gettid)
#endif
typedef unsigned long int __cpu_mask;
# define __CPUELT(cpu) ((cpu) / __NCPUBITS)
# define __CPUMASK(cpu) ((__cpu_mask) 1 << ((cpu) % __NCPUBITS))
typedef struct
{
unsigned long __bits[CPU_SETSIZE / __NCPUBITS];
} cpu_set_t;
#define CPU_SET(cpu, cpusetp) \
((__cpu_mask *)((cpusetp)->__bits))[__CPUELT (cpu)] |= __CPUMASK (cpu)
#define CPU_ZERO(cpusetp) \
memset((cpusetp), 0, sizeof(cpu_set_t))
#define CPU_ISSET(cpu, cpusetp) \
((((const __cpu_mask *)((cpusetp)->__bits))[__CPUELT (cpu)] & __CPUMASK (cpu))) != 0
#define CPU_CLR(cpu, cpusetp) \
(((__cpu_mask *)((cpusetp)->__bits))[__CPUELT (cpu)] &= ~__CPUMASK (cpu))
#define DEFINED_HERE "yes"
#endif
#ifndef DEFINED_HERE
#define DEFINED_HERE "no"
#endif
void setCurrentThreadAffinityMask(cpu_set_t mask)
{
int err, syscallres;
pid_t pid = gettid();
syscallres = syscall(__NR_sched_setaffinity, pid, sizeof(mask), &mask);
if (syscallres)
{
err = errno;
printf("Error in the syscall setaffinity: err=%d=0x%x", err, err);
}
}
int getCPUCount()
{
cpu_set_t cs;
CPU_ZERO(&cs);
int syscallres;
syscallres = syscall(__NR_sched_setaffinity, 0, sizeof(cs), &cs);
int count = 0;
for (int i = 0; i < 100; i++)
{
if (CPU_ISSET(i, &cs))
count++;
}
return count;
}
int main() {
printf("%s", DEFINED_HERE);
cpu_set_t mask;
long long j = 0;
int count = getCPUCount();
for (int i = 0; i < count; ++i) {
CPU_ZERO(&mask);
CPU_SET(i, &mask);
setCurrentThreadAffinityMask(mask);
printf("%d\n", i);
while (1) {
j++;
if (j == 2000000000L) break;
}
j = 0;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment