https://gcc.gnu.org/bugzilla/show_bug.cgi?id=113444

            Bug ID: 113444
           Summary: hardware_concurrency should take into account CPU
                    affinity
           Product: gcc
           Version: unknown
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: libstdc++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: kiwixz at outlook dot com
  Target Milestone: ---

It's very common for C++ programs to use std::thread::hardware_concurrency() to
evaluate the available concurrency on the machine, for example to limit the
number of threads in a pool.
As far as I understand the standard lets full freedom to the implementation to
return what it considers to be "The number of hardware thread contexts." or
even 0 if it can't reasonably define it.

I think this particular function should take into account CPU affinity
(sched_getaffinity on Linux) of the process for the same reason libgomp does
(see bug 64719): other processors are not accessible anyway so we might as well
not advertise them.
I don't think anyone rely on this value being the exact number of physical
processors, and especially not in any context where CPU affinity would be
altered. 

Related: a pull request I made in vcpkg to work around this exact issue
https://github.com/microsoft/vcpkg-tool/pull/1325

$ cat main.cpp 
#include <iostream>
#include <thread>

int main() {
    std::cout << std::thread::hardware_concurrency() << '\n';
}

// current on my machine
$ g++ main.cpp && taskset 1 ./a.out
12  

// what I would prefer
$ g++ main.cpp && taskset 1 ./a.out
1

Reply via email to