不管是线程还是进程,都是通过设置亲和性(affinity)来达到目的。 与进程的情况相似,线程亲和性的设置和获取主要通过下面两个函数来实现: int pthread_setaffinity_np(pthread_tthread, size_t cpusetsize,const cpu_set_t *cpuset); int pthread_getaffinity_np(pthread_t thread, size_t cpusetsize, cpu_set_t *cpuset); 从函数名以及参数名都很明了,唯一需要点解释下的可能就是cpu_set_t这个结构体了。这个结构体的理解类似于select中的fd_set,可以理解为cpu集,也是通过约定好的宏来进行清除、设置以及判断: //初始化,设为空 void CPU_ZERO (cpu_set_t *set); //将某个cpu加入cpu集中 void CPU_SET (int cpu, cpu_set_t *set); //将某个cpu从cpu集中移出 void CPU_CLR (int cpu, cpu_set_t *set); //判断某个cpu是否已在cpu集中设置了 int CPU_ISSET (int cpu, const cpu_set_t *set); cpu集可以认为是一个掩码,每个设置的位都对应一个可以合法调度的 cpu,而未设置的位则对应一个不可调度的 CPU。换而言之,线程都被绑定了,只能在那些对应位被设置了的处理器上运行。通常,掩码中的所有位都被置位了,也就是可以在所有的cpu中调度。 使用函数pthread_attr_setaffinity_np #include <stdio.h> #include <pthread.h> #include <unistd.h> int GetCpuCount() { return (int)sysconf(_SC_NPROCESSORS_ONLN); } void *thread_fun() { int i; while(1) { i = 0; } return NULL; } int main() { int cpu_num = 0; cpu_num = GetCpuCount(); printf("The number of cpu is %d\n", cpu_num); pthread_t t1; pthread_t t2; pthread_attr_t attr1; pthread_attr_t attr2; pthread_attr_init(&attr1); pthread_attr_init(&attr2); cpu_set_t cpu_info; __CPU_ZERO(&cpu_info); __CPU_SET(0, &cpu_info); if (0!=pthread_attr_setaffinity_np(&attr1, sizeof(cpu_set_t), &cpu_info)) { printf("set affinity failed"); return; } __CPU_ZERO(&cpu_info); __CPU_SET(1, &cpu_info); if (0!=pthread_attr_setaffinity_np(&attr2, sizeof(cpu_set_t), &cpu_info)) { printf("set affinity failed"); } if (0!=pthread_create(&t1, &attr1, thread_fun, NULL)) { printf("create thread 1 error\n"); return; } if (0!=pthread_create(&t2, &attr2, thread_fun, NULL)) { printf("create thread 2 error\n"); return; } pthread_join(t1, NULL); pthread_join(t2, NULL); } 使用函数pthread_setaffinity_np #include <stdio.h> #include <pthread.h> #include <unistd.h> int GetCpuCount() { return (int)sysconf(_SC_NPROCESSORS_ONLN); } void *thread_fun() { int i; while(1) { i = 0; } return NULL; } int main() { int cpu_num = 0; cpu_num = GetCpuCount(); printf("The number of cpu is %d\n", cpu_num); pthread_t t1; pthread_t t2; pthread_attr_t attr1; pthread_attr_t attr2; pthread_attr_init(&attr1); pthread_attr_init(&attr2); if (0!=pthread_create(&t1, &attr1, thread_fun, NULL)) { printf("create thread 1 error\n"); return; } if (0!=pthread_create(&t2, &attr2, thread_fun, NULL)) { printf("create thread 2 error\n"); return; } cpu_set_t cpu_info; __CPU_ZERO(&cpu_info); __CPU_SET(0, &cpu_info); if (0!=pthread_setaffinity_np(t1, sizeof(cpu_set_t), &cpu_info)) { printf("set affinity failed"); } __CPU_ZERO(&cpu_info); __CPU_SET(1, &cpu_info); if (0!=pthread_setaffinity_np(t2, sizeof(cpu_set_t), &cpu_info)) { printf("set affinity failed"); } pthread_join(t1, NULL); pthread_join(t2, NULL); } (责任编辑:IT) |