ObzLib threading
obz::thread_affinity
Small helpers for pinning the current thread to a logical CPU when the platform supports it.
Dedicated Work On Dedicated CPUs
Some systems have a thread that is meant to do one job repeatedly: audio mixing, polling hardware, collecting samples, running a benchmark loop, or feeding a low-latency simulation step.
In those cases, moving between CPUs can be noise. thread_affinity gives that worker a
small, explicit request: keep this current thread on this logical CPU.
std::jthread simulation_thread([](std::stop_token stop) {
if (!obz::try_pin_current_thread_to_cpu(2)) {
return;
}
while (!stop.stop_requested()) {
run_simulation_tick();
}
});
Pin The Thread From Inside The Thread
The library pins the current thread only. That keeps the API difficult to misuse: the worker decides where it wants to run after it has started, instead of another part of the program reaching in and changing thread state from the outside.
std::thread worker([] {
obz::pin_current_thread_to_cpu(3);
run_dedicated_worker();
});
worker.join();
The CPU number is a logical CPU index. It is not a promise about physical cores, cache topology, processor groups, or NUMA placement. It is the unit of placement the operating system exposes here.
Required Or Optional
Affinity is often an optimization, so the non-throwing function returns a simple success flag. That lets a program continue normally when the platform is unsupported or the operating system rejects the request.
if (obz::try_pin_current_thread_to_cpu(1)) {
run_latency_sensitive_loop();
} else {
run_regular_worker_loop();
}
When pinning is part of the execution model, the throwing function makes failure visible. Invalid indexes and operating-system failures become ordinary exceptions instead of silent scheduler guesses.
One API, Platform-Specific Work
Thread affinity is not a portable C++ feature. The useful design choice is that the public header stays small while the platform files do the operating-system work.
if (WIN32)
target_sources(obz_thread_affinity
PRIVATE
src/platform/win32_thread_affinity.cpp
)
elseif (CMAKE_SYSTEM_NAME STREQUAL "Linux")
target_sources(obz_thread_affinity
PRIVATE
src/platform/linux_thread_affinity.cpp
)
else()
target_sources(obz_thread_affinity
PRIVATE
src/platform/unsupported_thread_affinity.cpp
)
endif()
Linux uses pthread_setaffinity_np. Windows uses SetThreadAffinityMask.
Other platforms still compile, but report that affinity is unsupported.