处理std :: thread :: hardware_concurrency()

时间:2015-01-15 19:14:02

标签: c++ multithreading c++11 g++ version

在关于std::thread的{​​{3}}中,我被建议使用std::thread::hardware_concurrency()。我在某个地方读过(我找不到它,看起来像是一个本地的代码存储库),这个特性没有在4.8之前的g ++版本中实现。

事实上,我与question用户处于同一受害者的位置。该函数将返回0.我在this中找到了答案用户实现。欢迎评论这个答案是否合适!

所以我想在我的代码中执行此操作:

unsinged int cores_n;
#if g++ version < 4.8
 cores_n = my_hardware_concurrency();
#else
 cores_n = std::thread::hardware_concurrency();
#endif

但是,我可以找到一种方法来实现这个结果。我该怎么办?

2 个答案:

答案 0 :(得分:5)

除了使用 GCC Common Predefined Macros 之外,还有另外一种方法:检查std::thread::hardware_concurrency()是否返回零意味着功能尚未实现。

unsigned int hardware_concurrency()
{
    unsigned int cores = std::thread::hardware_concurrency();
    return cores ? cores : my_hardware_concurrency();
}

您可能会受到awgn's source code(GPL v2许可)的启发,以实施my_hardware_concurrency()

auto my_hardware_concurrency()
{
    std::ifstream cpuinfo("/proc/cpuinfo");

    return std::count(std::istream_iterator<std::string>(cpuinfo),
                      std::istream_iterator<std::string>(),
                      std::string("processor"));
}

答案 1 :(得分:1)

基于Joachim友好提供的常见预定义宏link,我做了:

int p;
#if __GNUC__ >= 5 || __GNUC_MINOR__ >= 8 // 4.8 for example
  const int P = std::thread::hardware_concurrency();
  p = (trees_no < P) ? trees_no : P;
  std::cout << P << " concurrent threads are supported.\n";
#else
  const int P = my_hardware_concurrency();
  p = (trees_no < P) ? trees_no : P;
  std::cout << P << " concurrent threads are supported.\n";
#endif