Linux下pthread的线程亲缘性研究
LINUX下可以使用pthread库提供的pthread_attr_setaffinity_np()设置线程亲缘性,理论上可以将某线程绑定在某CPU上执行。 编写测试程序的过程中发现,我的测试环境的glibc库的版本为2.3.4,要使用pthread_attr_setaffinity_np()函数必须要包含来代替,然后编译能够通过,链接的时候出现pthread_attr_setaffinity_np()函数未定义。 后来换到glibc2.8下,需要包含,编译链接执行一切顺利。 在glib2.3.4下使用无法使用线程亲缘性的函数,希望有这方面经验的朋友给予指点,谢谢! 下面是测试线程亲缘性的代码: //========================================================== //本程序演示如何设置线程亲缘性 #include //注意这个GLIBC的版本定义的宏 //测试发现,在glibc 2.3.4中,可以程序可以编译通过,但是链接的时候无法找到pthread_attr_setaffinity_np函数 // 在glibc2.8中,可以正常编译和链接,执行正常 #if __GLIBC__ == 2 && __GLIBC_MINOR__>3 #include #else #include #endif #include #include #include /// 得到CPU的核数 int GetCpuCount() { return (int)sysconf(_SC_NPROCESSORS_ONLN); //_SC_NPROCESSORS_ONLN 在confname.h中定义 } #ifndef P #define P(format, ...) do \ { \ fprintf(stdout, "%s %s %d " format "\n", __FILE__, __FUNCTION__, __LINE__, ##__VA_ARGS__); \ fflush(stdout); \ } \ while (0); #endif static int operator-(struct timeval& lsh, struct timeval& rsh) { if (lsh.tv_sec==rsh.tv_sec) { return lsh.tv_usec - rsh.tv_usec; } else { return (lsh.tv_sec-rsh.tv_sec)*1000000 + (lsh.tv_usec - rsh.tv_usec); } } void* _Add(void* param) { struct timeval start; struct timeval end; gettimeofday(&start, NULL); volatile double sum = 0.0; #define MAX_NUM 1000000000 for (int i=0; i