-2

I have C++ code that uses

int nthreads = thread::hardware_concurrency();

When I try to build my application on some computers, I get the error message

error: 'thread' has not been declared

I do not ask how to solve the error. I'm more interested in if there is a special "guard" that I can use to simply remove the lines of code by the preprocessor like for example in OpenMP I can use:

#ifdef _OPENMP
...
#endif
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
user7431005
  • 3,899
  • 4
  • 22
  • 49
  • 4
    Are you asking the right question? Sounds like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Solving the error would be better than trying to detect when you need to avoid it. – 1201ProgramAlarm Jul 18 '18 at 21:12
  • "*error: 'thread' has not been declared*" - did you remember to use `#include `? And probably also `using namespace std;` or better `using std::thread;` since you are not fully qualifying `hardware_concurrency()` as `std::thread::hardware_concurrency()`, only as `thread::hardware_concurrency()` – Remy Lebeau Jul 19 '18 at 00:13

1 Answers1

4

std::thread::hardware_concurrency is provided by C++11. If compilers on those "some computers" support it you may have to toggle C++11 support (e.g. with mingw/gcc -std=c++11).

To disable hardware_concurrency usage when unavailable, the best solution might be to detect C++11 support.

This answer may work out for you, even if you use Visual Studio:

#if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900)
    int nthreads = std::thread::hardware_concurrency();
#else
    int nthreads = 4; // whatever fallback value
#endif

Do note that it detects the VS 2015 compiler version as it was the first one to advertize full C++11 support. You can tweak the _MSC_VER check to an older version if hardware_concurrency happens to be available on older VS compilers.

asu
  • 1,875
  • 17
  • 27