Skip to content

Commit 50723a0

Browse files
committed
Honor CPU affinity in ThreadPool::getNumCores
This reports that number of CPUs that are actually usable by the current process. This means that I can do something like `taskset -c 0 emcc hello.c -O2` and the internal call to `wasm-opt` within emcc will only use a single core. Ideally this would work on macOS and windows too, but I'm not even sure how easy it is to control affinity on those OSes.
1 parent 36366d2 commit 50723a0

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/support/threads.cpp

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,21 @@
2020
#include <iostream>
2121
#include <string>
2222

23+
#ifdef __linux__
24+
#include <sched.h> // For sched_getaffinity
25+
#endif
26+
2327
#include "compiler-support.h"
2428
#include "threads.h"
2529
#include "utilities.h"
30+
#include "support/debug.h"
2631

2732
// debugging tools
2833

34+
// DEBUG_TYPE is for BYN_TRACE macro. This tracing can be enabled at runtime
35+
#define DEBUG_TYPE "threads"
36+
37+
// BINARYEN_THREAD_DEBUG is a build-time setting for detailed thread tracing
2938
#ifdef BINARYEN_THREAD_DEBUG
3039
static std::mutex debug;
3140
#define DEBUG_THREAD(x) \
@@ -145,9 +154,22 @@ size_t ThreadPool::getNumCores() {
145154
return 1;
146155
#else
147156
size_t num = std::max(1U, std::thread::hardware_concurrency());
157+
#ifdef __linux__
158+
// On linux we can do better since we can get the number of CPU that are
159+
// actually usable by the current process.
160+
cpu_set_t cpu_set;
161+
CPU_ZERO(&cpu_set);
162+
if (sched_getaffinity(0, sizeof(cpu_set), &cpu_set) == 0) {
163+
num = 0;
164+
for (int i = 0; i < CPU_SETSIZE; i++) {
165+
if (CPU_ISSET(i, &cpu_set)) num++;
166+
}
167+
}
168+
#endif
148169
if (getenv("BINARYEN_CORES")) {
149170
num = std::stoi(getenv("BINARYEN_CORES"));
150171
}
172+
BYN_TRACE("getNumCores: " << num << "\n");
151173
return num;
152174
#endif
153175
}

0 commit comments

Comments
 (0)