cmAffinity.cxx 1.52 KB
Newer Older
1 2 3 4 5 6 7
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file Copyright.txt or https://cmake.org/licensing for details.  */
#include "cmAffinity.h"

#include "cm_uv.h"

#ifndef CMAKE_USE_SYSTEM_LIBUV
8 9 10 11 12 13 14 15 16 17 18 19 20
#  ifdef _WIN32
#    define CM_HAVE_CPU_AFFINITY
#    include <windows.h>
#  elif defined(__linux__) || defined(__FreeBSD__)
#    define CM_HAVE_CPU_AFFINITY
#    include <pthread.h>
#    include <sched.h>
#    if defined(__FreeBSD__)
#      include <pthread_np.h>
#      include <sys/cpuset.h>
#      include <sys/param.h>
#    endif
#    if defined(__linux__)
21
typedef cpu_set_t cm_cpuset_t;
22
#    else
23
typedef cpuset_t cm_cpuset_t;
24 25
#    endif
#  endif
26 27 28 29 30 31 32 33 34 35
#endif

namespace cmAffinity {

std::set<size_t> GetProcessorsAvailable()
{
  std::set<size_t> processorsAvailable;
#ifdef CM_HAVE_CPU_AFFINITY
  int cpumask_size = uv_cpumask_size();
  if (cpumask_size > 0) {
36
#  ifdef _WIN32
37 38 39 40 41 42 43 44 45 46
    DWORD_PTR procmask;
    DWORD_PTR sysmask;
    if (GetProcessAffinityMask(GetCurrentProcess(), &procmask, &sysmask) !=
        0) {
      for (int i = 0; i < cpumask_size; ++i) {
        if (procmask & (((DWORD_PTR)1) << i)) {
          processorsAvailable.insert(i);
        }
      }
    }
47
#  else
48 49 50 51 52 53 54 55 56
    cm_cpuset_t cpuset;
    CPU_ZERO(&cpuset); // NOLINT(clang-tidy)
    if (pthread_getaffinity_np(pthread_self(), sizeof(cpuset), &cpuset) == 0) {
      for (int i = 0; i < cpumask_size; ++i) {
        if (CPU_ISSET(i, &cpuset)) {
          processorsAvailable.insert(i);
        }
      }
    }
57
#  endif
58 59 60 61 62
  }
#endif
  return processorsAvailable;
}
}