修正 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

@ -15,65 +15,68 @@
#include <sys/syscall.h>
int SetProcessAffinity(void) {
cpu_set_t set;
pid_t pid = getpid();
cpu_set_t set;
pid_t pid = getpid();
// 进程只在核 3 和核 7 上执行.
CPU_ZERO(&set);
CPU_SET(3, &set);
CPU_SET(7, &set);
// 进程只在核 3 和核 7 上执行.
CPU_ZERO(&set);
CPU_SET(3, &set);
CPU_SET(7, &set);
int res, err;
(void)res;
(void)err;
res = sched_setaffinity(pid, sizeof(set), &set);
err = errno;
int res, err;
(void)res;
(void)err;
res = sched_setaffinity(pid, sizeof(set), &set);
err = errno;
return res;
return res;
}
void SetThreadAffinity(int mask) {
int err, syscallres;
pid_t pid = gettid();
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) {
err = errno;
}
syscallres = syscall(__NR_sched_setaffinity, pid, cpusetsize, cpuset);
if(syscallres)
err = errno;
}
void* DemoRoutine0(void* arg)
{
(void)arg;
// DemoRoutine0 只运行在核 3 上.
SetThreadAffinity(1<<3);
while(1);
return nullptr;
(void)arg;
cpu_set_t set;
CPU_ZERO(&set);
// DemoRoutine0 只运行在核 3 上.
CPU_SET(3, &set);
SetThreadAffinity(sizeof(set), &set);
while(1);
return nullptr;
}
void* DemoRoutine1(void* arg)
{
(void)arg;
// DemoRoutine0 只运行在核 7 上.
SetThreadAffinity(1<<7);
while(1);
return nullptr;
(void)arg;
cpu_set_t set;
CPU_ZERO(&set);
// DemoRoutine0 只运行在核 7 上.
CPU_SET(7, &set);
SetThreadAffinity(sizeof(set), &set);
while(1);
return nullptr;
}
int main(void)
{
pthread_t demoThrd0, demoThrd1;
cpu_set_t set;
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]);
SetProcessAffinity();
sched_getaffinity(getpid(), sizeof(set), &set);
printf("Current CPU Setbits=%lu.\r\n", set.__bits[0]);
pthread_create(&demoThrd0, nullptr, DemoRoutine0, nullptr);
pthread_create(&demoThrd1, nullptr, DemoRoutine1, nullptr);
pthread_join(demoThrd0, nullptr);
pthread_join(demoThrd1, nullptr);
return 0;
pthread_create(&demoThrd0, nullptr, DemoRoutine0, nullptr);
pthread_create(&demoThrd1, nullptr, DemoRoutine1, nullptr);
pthread_join(demoThrd0, nullptr);
pthread_join(demoThrd1, nullptr);
return 0;
}