#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sched.h>
#include <unistd.h>
struct Message{
int num;
char msg[32];
};
void bind_cpu(void *ptr);
void WasteTime();
void WasteTime(){
int abc = 1000000;
while(1){
int tmp = 10000 * 10000;
}
}
void bind_cpu(void *ptr){
struct Message *message = (struct Message *)ptr;
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(message->num, &mask);
printf("print message function \t %s\n", (char *)(message->msg));
if(pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask) < 0){
printf("print message function \t %s\n", (char *)(message->msg));
}
WasteTime();
}
int main(){
// 局部变量
int i;
char info[32];
struct Message messages[3];
// 当前cpu核数, 可使用cpu核数
int cpu_number = sysconf(_SC_NPROCESSORS_CONF);
int enable_cpu_number = sysconf(_SC_NPROCESSORS_ONLN);
printf("当前cpu核数 %d\n", cpu_number);
// 初始化线程绑定信息
for(i = 0; i < cpu_number; i ++){
sprintf(info, "%d", i);
messages[i].num = i;
strcpy(messages[i].msg, info);
}
for(i = 0; i < cpu_number; i ++){
printf("messages[%d].num is %d \n", i, messages[i].num);
printf("messages[%d].msg is %s \n", i, messages[i].msg);
}
// 创建线程
int ret_thr[cpu_number];
pthread_t thread[cpu_number];
for(i = 0; i < cpu_number; i ++){
ret_thr[i] = pthread_create(&thread[i], NULL, (void *)&bind_cpu, (void *)&messages[i]);
}
// 查看线程是否创建成功
for(i = 0; i < cpu_number; i ++){
if(ret_thr[i] != 0){
printf("thr%d create failed\n", i);
}else{
printf("thr%d create success\n", i);
}
}
// 阻塞进程,查看阻塞是否成功
int tmp[cpu_number];
void *retval;
for(i = 0; i < cpu_number; i ++){
tmp[i] = pthread_join(thread[i], &retval);
if(tmp[i] != 0){
printf("thr%d join failed\n", i);
}else{
printf("thr%d join success\n", i);
}
}
return 0;
}
linux - 启动多线程绑定cpu
最新推荐文章于 2022-09-22 10:07:36 发布