Handle std::thread::hardware_concurrency()

前端 未结 2 660
轻奢々
轻奢々 2021-02-11 00:25

In my question about std::thread, I was advised to use std::thread::hardware_concurrency(). I read somewhere (which I can not find it and seems like a

2条回答
  •  既然无缘
    2021-02-11 01:20

    There is another way than using the GCC Common Predefined Macros: Check if std::thread::hardware_concurrency() returns zero meaning the feature is not (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's source code (GPL v2 licensed) to implement my_hardware_concurrency()

    auto my_hardware_concurrency()
    {
        std::ifstream cpuinfo("/proc/cpuinfo");
    
        return std::count(std::istream_iterator(cpuinfo),
                          std::istream_iterator(),
                          std::string("processor"));
    }
    

提交回复
热议问题