修正 SetThreadAffinity 接口,调整代码格式.

Signed-off-by: rick.chan <chenyang@autoai.com>
This commit is contained in:
rick.chan 2021-06-07 16:50:29 +08:00
parent bba3271108
commit f498e91191
1 changed files with 44 additions and 41 deletions

View File

@ -32,21 +32,23 @@ int SetProcessAffinity(void) {
return res;
}
void SetThreadAffinity(int mask) {
void SetThreadAffinity(size_t cpusetsize, cpu_set_t *cpuset) {
int err, syscallres;
pid_t pid = gettid();
// Linux 下可以直接使用 pthread_setaffinity_np() 函数将当前线程绑定在具体的 CPU 上, 而 Android 屏蔽了该 API, 需要通过 syscall(__NR_sched_setaffinity) 来实现.
syscallres = syscall(__NR_sched_setaffinity, pid, sizeof(mask), &mask);
if (syscallres) {
syscallres = syscall(__NR_sched_setaffinity, pid, cpusetsize, cpuset);
if(syscallres)
err = errno;
}
}
void* DemoRoutine0(void* arg)
{
(void)arg;
cpu_set_t set;
CPU_ZERO(&set);
// DemoRoutine0 只运行在核 3 上.
SetThreadAffinity(1<<3);
CPU_SET(3, &set);
SetThreadAffinity(sizeof(set), &set);
while(1);
return nullptr;
}
@ -54,8 +56,11 @@ void* DemoRoutine0(void* arg)
void* DemoRoutine1(void* arg)
{
(void)arg;
cpu_set_t set;
CPU_ZERO(&set);
// DemoRoutine0 只运行在核 7 上.
SetThreadAffinity(1<<7);
CPU_SET(7, &set);
SetThreadAffinity(sizeof(set), &set);
while(1);
return nullptr;
}
@ -65,11 +70,9 @@ int main(void)
pthread_t demoThrd0, demoThrd1;
cpu_set_t set;
sched_getaffinity(getpid(), sizeof(set), &set);
printf("Init CPU Setbits=%lu.\r\n", set.__bits[0]);
SetProcessAffinity();
sched_getaffinity(getpid(), sizeof(set), &set);
printf("Init CPU Setbits=%lu.\r\n", set.__bits[0]);
printf("Current CPU Setbits=%lu.\r\n", set.__bits[0]);
pthread_create(&demoThrd0, nullptr, DemoRoutine0, nullptr);
pthread_create(&demoThrd1, nullptr, DemoRoutine1, nullptr);