Handle std :: thread :: hardware_concurrency ()

In a question about std::thread

I was advised to use std::thread::hardware_concurrency()

. I read somewhere (which I can't find and looks like a local code repository or whatever) this feature is not implemented for g ++ versions prior to 4.8.

In fact, I was in the same victim position as this user. The function will just return 0. I found this for a custom implementation answer. Comments on whether this answer is good or not are welcome!

So I would like to do this in my code:

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

      

However, I could find a way to achieve this result. What should I do?

+2


source to share


2 answers


There is another way than using the GCC General Predefined Macros : check if std::thread::hardware_concurrency()

zero is returned , which means the feature has not been installed (yet) implemented.

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

      



You may be inspired by awgn source code (GPL v2 license) to implementmy_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"));
}

      

+4


source


Based on the common predefined macros link courtesy of Joachim I did:



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

      

+1


source







All Articles