创建线程并绑定到相应的cpu核上

源代码:

#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, &param)) {
        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号:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值