在某些特殊场景,多程之间的切换和调度会影响性能和效率,那么怎样才能提高效率和性能呢?
多核绑定可以轻易的解决这个问题,将程绑定到固定的cpu上减少多程之间的调度和切换。
#include <pthread.h>
#include <unistd.h>
void bindCpu(int id)//id为需要绑定的CPU的Id号
{
cpu_set_t mask;
cpu_set_t get;
int j;
int num = sysconf(_SC_NPROCESSORS_CONF);
printf("system has %d processor(s)\n", num);
CPU_ZERO(&mask);
CPU_SET(id, &mask);
if (pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask) < 0) {
fprintf(stderr, "set thread affinity failed\n");
}
CPU_ZERO(&get);
if (pthread_getaffinity_np(pthread_self(), sizeof(get), &get) < 0) {
fprintf(stderr, "get thread affinity failed\n");
}
for (j = 0; j < num; j++) {
if (CPU_ISSET(j, &get)) {
printf("thread %d is running in processor %d\n", (int)pthread_self(), j);
}
}
}
这部分代码直接适用于线程中