创建线程并绑定到相应的cpu核上
程序员文章站
2022-06-28 18:24:42
...
源代码:
#include <pthread.h>
#include <stdio.h>
#define _GNU_SOURCE
#include <sched.h>
static pthread_t cyclic_thread;
static struct param_t {
int cpu_number;
int enable_affinity;
};
static void *my_thread(void *param){
cpu_set_t mask;
pthread_t thread;
struct param_t *par = param;
if (par->enable_affinity != -1) {
CPU_ZERO(&mask);
CPU_SET(par->cpu_number, &mask);
thread = pthread_self();
if (pthread_setaffinity_np(thread, sizeof(mask), &mask) == -1)
warn("Could not set CPU affinity to CPU #%d\n",
par->cpu_number);
}
while(1){
printf("set CPU affinity to CPU is sucessful\n");
sleep(1);
}
}
int main(int argc, char const *argv[])
{
/* Create cyclic RT-thread */
struct param_t param;
param.cpu_number = 1;
param.enable_affinity = 1;
pthread_attr_t thattr;
pthread_attr_init(&thattr);
pthread_attr_setdetachstate(&thattr, PTHREAD_CREATE_JOINABLE);
if (pthread_create(&cyclic_thread, &thattr, &my_thread, ¶m)) {
fprintf(stderr, "pthread_create cyclic task failed\n");
return 1;
}
pthread_join(cyclic_thread, NULL);
return 0;
}
//编译的方式 gcc test.c -lpthread -D_GNU_SOURCE
验证方式:
运行程序,使用命令top查看指定的进程的PID:
然后使用命令:
top -H -p PID
按f键,并使用上下切换,利用空格键选中nTH,P:
按esc键,P所在的列就是线程运行的CPU号:
推荐阅读