線程與內核綁定

多內核主機上,創建了多個線程,可以把線程綁定到指定的內核上。

這樣可以充分發揮多個內核的性能優勢,減少上下文切換。


線程與內核綁定方法:

1、頭文件 

#include <sys/sysinfo.h>

#include <pthread.h>


2、綁定

1)獲取cpu內核數目

int cpu_num = get_nprocs(); 

2)創建多個線程

pthread_t thread_id;

pthread_create(&thread_id, NULL, threadFunc, NULL); 

2)根據內核索引號綁定線程,內核索引號cpu_index(從0到cpu_num)

cpu_set_t mask;

CPU_ZERO(&mask);

CPU_SET(cpu_index, &mask);

pthread_setaffinity_np(thread_id, sizeof(mask), &mask) ;

3)獲取線程綁定的內核索引號,判斷是否綁定成功

CPU_ZERO(&mask);

pthread_getaffinity_np(thread_id, sizeof(mask), &mask);

CPU_ISSET(cpu_index, &mask);




netstat –apn | grep 8080 查看端口號




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章