可能重复:
以编程方式查找机器上的核心数量
什么是POSIX或x86,x86-64特定的系统调用来确定系统可以运行的最大线程数量,而不会超额预订? 谢谢。
它使用C兼容的结构,为什么不使用实际的代码呢? [库/线程/ SRC / * / thread.cpp]
使用pthread库:
unsigned thread::hardware_concurrency() { #if defined(PTW32_VERSION) || defined(__hpux) return pthread_num_processors_np(); #elif defined(__APPLE__) || defined(__FreeBSD__) int count; size_t size=sizeof(count); return sysctlbyname("hw.ncpu",&count,&size,NULL,0)?0:count; #elif defined(BOOST_HAS_UNISTD_H) && defined(_SC_NPROCESSORS_ONLN) int const count=sysconf(_SC_NPROCESSORS_ONLN); return (count>0)?count:0; #elif defined(_GNU_SOURCE) return get_nprocs(); #else return 0; #endif }
在Windows中:
unsigned thread::hardware_concurrency() { SYSTEM_INFO info={{0}}; GetSystemInfo(&info); return info.dwNumberOfProcessors; }