1、安裝 taskset
lark@ubuntu:~$ sudo apt-get install util-linux
lark@ubuntu:~$ taskset --help
用法: taskset [選項] [mask | cpu-list] [pid|cmd [args...]]
顯示或更改進程的 CPU 關聯性。選項:
-a, --all-tasks 對給定 pid
的所有任務(線程)進行作 -p, --pid 對現有的給定 pid
進行作 -c, --cpu-list display 并以列表格式
指定 cpu -h, --help 顯示此幫助
-V, --version 顯示版本默認行為是運行新命令:
taskset 03 sshd -b 1024
您可以檢索現有任務的掩碼:
taskset -p 700
或設置它:
taskset -p 03 700
列表格式使用逗號分隔的列表而不是掩碼:
taskset -pc 0,3,7-11 700
列表格式的范圍可以采用 stride 參數:
例如,0-31:2 等同于掩碼 0x55555555有關更多詳細信息,請參閱 taskset(1)。
2,,查詢確認系統是幾個核的
lark@ubuntu:~$ cat /proc/cpuinfo |grep “processor”
處理器 : 0
處理器 : 1
處理器 : 2
處理器 : 3
處理器 : 4
處理器 : 5
處理器 : 6
處理器 : 7
lark@ubuntu:~$ taskset -c -p 3109
PID 3109 的當前親和力列表:0-7
lark@ubuntu:~$ taskset -a -p 3554
pid 3554 的當前親和掩碼:ff
綁定內核,指定進程pid在cpu_id上 taskset -pc cpu_id PID
lark@ubuntu:~$ taskset -c -p 3109
pid 3109 的當前親和值列表:0-7
lark@ubuntu:~$
lark@ubuntu:~$ taskset -pc 1 3109
PID 3109 的當前親和值列表:0-7
PID 3109 的新親和值列表:1
lark@ubuntu:~$ taskset -c -p 3109
PID 3109 的當前親和值列表:1
更改具體某一進程(或 線程)CPU親和性
taskset -p hexadecimal mask PID/LWP
上面號線程可以在0~3號CPU之間允許,現在設置掩碼0x11(二進制0001 0001),表示可以在0~3號CPU上允許。
為具體某一進程(或 線程)CPU親和性指定一組范圍
lark@ubuntu:~$ taskset -pc 0,1,2 3109
pid 3109 的當前親和力列表:7
pid 3109 的新親和力列表:0-2
lark@ubuntu:~$ taskset -c -p 3109
pid 3109 當前的親和力列表:0-2
3,內核態函數綁定cpu以及用戶態綁定cpu舉例?
sched_setaffinity()
:綁定線程到 CPU 核心。
#define _GNU_SOURCE
#include <stdio.h>
#include <sched.h>
#include <pthread.h> void* thread_func(void* arg) { cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(1, &cpuset); // 綁定到 CPU 1 if (sched_setaffinity(0, sizeof(cpu_set_t), &cpuset) == -1) { perror("sched_setaffinity failed"); } while (1); // 模擬線程工作 return NULL;
} int main() { pthread_t thread; pthread_create(&thread, NULL, thread_func, NULL); pthread_join(thread, NULL); return 0;
}
2,內核態綁定cpu,set_cpus_allowed_ptr()
:設置內核線程的 CPU 親和性
<linux/kthread.h>
#include <linux/cpumask.h> static int kernel_thread_func(void* data) { cpumask_var_t mask; alloc_cpumask_var(&mask, GFP_KERNEL); cpumask_clear(mask); cpumask_set_cpu(2, mask); // 綁定到 CPU 2 set_cpus_allowed_ptr(current, mask); while (!kthread_should_stop()) { // 內核線程任務 } return 0;
} static int __init init_module(void) { struct task_struct *task = kthread_run(kernel_thread_func, NULL, "kbind_thread"); return 0;
}
用戶態通過sched_setaffinity()??綁定線程,內核態需操作?cpumask和任務調度器綁定內核線程。