【问题标题】:remove thread::hardware_concurrency by preprocessor if not declared如果未声明,则通过预处理器删除 thread::hardware_concurrency
【发布时间】:2018-07-18 20:06:15
【问题描述】:

我有使用的 C++ 代码

int nthreads = thread::hardware_concurrency();

当我尝试在某些计算机上构建我的应用程序时,我收到错误消息

error: 'thread' has not been declared

我不问如何解决错误。我更感兴趣的是是否有一个特殊的“守卫”,我可以使用它来简单地通过预处理器删除代码行,例如在我可以使用的 OpenMP 中:

#ifdef _OPENMP
...
#endif

【问题讨论】:

  • 您问的问题对吗?听起来像XY problem。解决错误比尝试检测何时需要避免它更好。
  • "error: 'thread' has not been declared" - 你记得使用#include <thread>吗?并且可能还有using namespace std; 或更好的using std::thread;,因为您没有完全将hardware_concurrency() 视为std::thread::hardware_concurrency(),仅作为thread::hardware_concurrency()

标签: c++ multithreading header c-preprocessor


【解决方案1】:

std::thread::hardware_concurrency 由 C++11 提供。如果那些“某些计算机”上的编译器支持它,您可能必须切换 C++11 支持(例如,使用 mingw/gcc -std=c++11)。

要在不可用时禁用hardware_concurrency,最好的解决方案可能是检测 C++11 支持。

This answer 可能适合您,即使您使用 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

请注意,它会检测 VS 2015 编译器版本,因为它是第一个宣传完整 C++11 支持的版本。如果 hardware_concurrency 恰好在较旧的 VS 编译器上可用,您可以将 _MSC_VER 检查调整为较旧的版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 2013-10-02
    • 1970-01-01
    相关资源
    最近更新 更多