CPU Affinity

用 pthread_setaffinity_np() 就可以指定 thread 用 CPU 的某幾個 core 去跑,直接看下面的 example,CPU core 編號從 0 開始。
#include <stdio.h>
#include <math.h>
#include <boost/bind.hpp>
#include <tbb/tbb_thread.h>

void func(int id, int cpu)
{
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(cpu, &mask);
if (pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask) < 0)
{
perror("pthread_setaffinity_np failed");
}

long tmp = 0;
long i = 0;
while (i < (cpu+1) * 100000000)
{
i++;
tmp += sqrt(i);
}

printf("thread %d: %ld\n", id, tmp);
}

int main ()
{
tbb::tbb_thread thread0(boost::bind(&func, 0, 3));
tbb::tbb_thread thread1(boost::bind(&func, 1, 2));
tbb::tbb_thread thread2(boost::bind(&func, 2, 1));
tbb::tbb_thread thread3(boost::bind(&func, 3, 0));

thread0.join();
thread1.join();
thread2.join();
thread3.join();

return 0;
}

0 comments:

張貼意見