Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[CPU][THREADING] Cache baseline process mask to prevent affinity poisoning in concurrent inference (#38492)

Wanglei Shen0a1f47c229ce
diff --git a/src/inference/src/dev/threading/cpu_streams_executor.cpp b/src/inference/src/dev/threading/cpu_streams_executor.cpp
index ad20a6f2f67..5f3757d6a0e 100644
--- a/src/inference/src/dev/threading/cpu_streams_executor.cpp
+++ b/src/inference/src/dev/threading/cpu_streams_executor.cpp
@@ -279,9 +279,6 @@ struct CPUStreamsExecutor::Impl {
std::unique_ptr<custom::task_arena> _taskArena;
std::unique_ptr<Observer> _observer;
std::vector<int> _cpu_ids;
-#elif OV_THREAD == OV_THREAD_SEQ
- CpuSet _mask = nullptr;
- int _ncpus = 0;
#endif
};
// if the thread is created by CPUStreamsExecutor, the Impl::Stream of the thread is stored by tbb Class
@@ -451,42 +448,39 @@ struct CPUStreamsExecutor::Impl {
} else {
task();
}
+#elif OV_THREAD == OV_THREAD_SEQ
+ if (_config.get_cpu_pinning()) {
+ ScopedThreadAffinity affinity_guard;
+ pin_stream_to_cpus(stream);
+ task();
+ } else {
+ task();
+ }
#else
- pin_stream_to_cpus();
task();
- unpin_stream_to_cpus();
#endif
}
- void pin_stream_to_cpus() {
+ void pin_stream_to_cpus(Stream& stream) {
#if OV_THREAD == OV_THREAD_SEQ
- if (_config.get_cpu_pinning()) {
- auto stream = _streams->local();
- auto proc_type_table = get_org_proc_type_table();
- std::tie(stream->_mask, stream->_ncpus) = get_process_mask();
- if (get_num_numa_nodes() > 1) {
- pin_current_thread_to_socket(stream->_numaNodeId);
- } else if (proc_type_table.size() == 1 && proc_type_table[0][EFFICIENT_CORE_PROC] == 0) {
- if (nullptr != stream->_mask) {
- pin_thread_to_vacant_core(stream->_streamId + _config.get_thread_binding_offset(),
- _config.get_thread_binding_step(),
- stream->_ncpus,
- stream->_mask);
- }
+ auto proc_type_table = get_org_proc_type_table();
+ // Use the process baseline mask for choosing a vacant core to pin to.
+ CpuSet process_mask;
+ int process_ncpus = 0;
+ std::tie(process_mask, process_ncpus) = get_process_mask();
+ if (get_num_numa_nodes() > 1) {
+ pin_current_thread_to_socket(stream._numaNodeId);
+ } else if (proc_type_table.size() == 1 && proc_type_table[0][EFFICIENT_CORE_PROC] == 0) {
+ if (nullptr != process_mask) {
+ pin_thread_to_vacant_core(stream._streamId + _config.get_thread_binding_offset(),
+ _config.get_thread_binding_step(),
+ process_ncpus,
+ process_mask);
}
}
#endif
}
- void unpin_stream_to_cpus() {
-#if OV_THREAD == OV_THREAD_SEQ
- auto stream = _streams->local();
- if (stream->_mask) {
- pin_current_thread_by_mask(stream->_ncpus, stream->_mask);
- }
-#endif
- }
-
void Defer(Task task) {
auto& stream = *(_streams->local());
stream._taskQueue.push(std::move(task));
diff --git a/src/inference/src/dev/threading/thread_affinity.cpp b/src/inference/src/dev/threading/thread_affinity.cpp
index a0c35657fed..ecd79e9d987 100644
--- a/src/inference/src/dev/threading/thread_affinity.cpp
+++ b/src/inference/src/dev/threading/thread_affinity.cpp
@@ -6,20 +6,25 @@
#include <cerrno>
#include <climits>
+#include <cstring>
#include <tuple>
#include <utility>
#include "openvino/runtime/system_conf.hpp"
+#include "os/cpu_map_info.hpp"
#if !(defined(__APPLE__) || defined(__EMSCRIPTEN__) || defined(_WIN32))
# include <sched.h>
# include <unistd.h>
+#elif defined(_WIN32)
+# include <windows.h>
#endif
namespace ov {
namespace threading {
#if !(defined(__APPLE__) || defined(__EMSCRIPTEN__) || defined(_WIN32))
-std::tuple<CpuSet, int> get_process_mask() {
+namespace {
+std::tuple<CpuSet, int> query_mask_impl(pid_t pid) {
for (int ncpus = sizeof(cpu_set_t) / CHAR_BIT; ncpus < 32768 /* reasonable limit of #cores*/; ncpus <<= 1) {
CpuSet mask{CPU_ALLOC(ncpus)};
if (nullptr == mask)
@@ -27,13 +32,39 @@ std::tuple<CpuSet, int> get_process_mask() {
const size_t size = CPU_ALLOC_SIZE(ncpus);
CPU_ZERO_S(size, mask.get());
// the result fits the mask
- if (0 == sched_getaffinity(getpid(), size, mask.get())) {
- return std::make_tuple(std::move(mask), ncpus);
+ if (0 == sched_getaffinity(pid, size, mask.get())) {
+ return {std::move(mask), ncpus};
}
// other error
if (errno != EINVAL)
break;
}
+ return {nullptr, 0};
+}
+} // namespace
+
+std::tuple<CpuSet, int> query_process_mask() {
+ return query_mask_impl(getpid());
+}
+
+std::tuple<CpuSet, int> query_thread_mask() {
+ return query_mask_impl(0);
+}
+
+std::tuple<CpuSet, int> get_process_mask() {
+ const auto& process_mask = cpu_info().get_process_mask_raw();
+ const int ncpus = cpu_info().get_process_mask_ncpus();
+ if (nullptr == process_mask) {
+ // Snapshot failed during startup; do not query the process mask live, as that re-introduces
+ // affinity poisoning from the main thread. Return an empty mask instead.
+ return std::make_tuple(nullptr, 0);
+ }
+ const size_t size = CPU_ALLOC_SIZE(ncpus);
+ CpuSet mask{CPU_ALLOC(ncpus)};
+ if (nullptr != mask) {
+ std::memcpy(mask.get(), process_mask.get(), size);
+ return std::make_tuple(std::move(mask), ncpus);
+ }
return std::make_tuple(nullptr, 0);
}
@@ -102,7 +133,8 @@ bool pin_current_thread_to_socket(int socket) {
for (int core = socket * cores_per_socket; core < (socket + 1) * cores_per_socket; core++) {
CPU_SET_S(core, size, targetMask.get());
}
- // respect the user-defined mask for the entire process
+ // Restrict to the process affinity baseline snapshotted once at first cpu_info() use
+ // (before OpenVINO pins any thread); later changes to process affinity are not observed.
CPU_AND_S(size, targetMask.get(), targetMask.get(), mask.get());
bool res = false;
if (CPU_COUNT_S(size, targetMask.get())) { // if we have non-zero mask to set
@@ -111,14 +143,30 @@ bool pin_current_thread_to_socket(int socket) {
return res;
}
#elif defined(_WIN32)
-std::tuple<CpuSet, int> get_process_mask() {
+std::tuple<CpuSet, int> query_process_mask() {
DWORD_PTR pro_mask, sys_mask;
if (0 != GetProcessAffinityMask(GetCurrentProcess(), &pro_mask, &sys_mask)) {
- CpuSet mask = std::make_unique<cpu_set_t>(pro_mask);
+ CpuSet mask = std::make_unique<cpu_set_t>(static_cast<cpu_set_t>(pro_mask));
return std::make_tuple(std::move(mask), 0);
}
return std::make_tuple(nullptr, 0);
}
+
+std::tuple<CpuSet, int> query_thread_mask() {
+ GROUP_AFFINITY ga{};
+ if (0 != GetThreadGroupAffinity(GetCurrentThread(), &ga)) {
+ return std::make_tuple(std::make_unique<cpu_set_t>(static_cast<cpu_set_t>(ga.Mask)), 0);
+ }
+ return std::make_tuple(nullptr, 0);
+}
+
+std::tuple<CpuSet, int> get_process_mask() {
+ const auto& process_mask = cpu_info().get_process_mask_raw();
+ if (nullptr == process_mask) {
+ return std::make_tuple(nullptr, 0);
+ }
+ return std::make_tuple(std::make_unique<cpu_set_t>(*process_mask), 0);
+}
void release_process_mask(cpu_set_t*) {}
bool pin_thread_to_vacant_core(int thrIdx,
@@ -145,13 +193,23 @@ bool pin_thread_to_vacant_core(int thrIdx,
}
}
bool pin_current_thread_by_mask(int ncores, const CpuSet& procMask) {
- DWORD_PTR mask = *procMask.get();
+ if (!procMask)
+ return false;
+ DWORD_PTR mask = static_cast<DWORD_PTR>(*procMask.get());
return 0 != SetThreadAffinityMask(GetCurrentThread(), mask);
}
bool pin_current_thread_to_socket(int socket) {
return false;
}
#else // no threads pinning/binding on MacOS
+std::tuple<CpuSet, int> query_process_mask() {
+ return std::make_tuple(nullptr, 0);
+}
+
+std::tuple<CpuSet, int> query_thread_mask() {
+ return std::make_tuple(nullptr, 0);
+}
+
std::tuple<CpuSet, int> get_process_mask() {
return std::make_tuple(nullptr, 0);
}
diff --git a/src/inference/src/dev/threading/thread_affinity.hpp b/src/inference/src/dev/threading/thread_affinity.hpp
index a58d05715db..0b48e6aa923 100644
--- a/src/inference/src/dev/threading/thread_affinity.hpp
+++ b/src/inference/src/dev/threading/thread_affinity.hpp
@@ -4,6 +4,7 @@
#pragma once
+#include <cstdint>
#include <memory>
#include <tuple>
#include <vector>
@@ -11,11 +12,6 @@
#if !(defined(__APPLE__) || defined(__EMSCRIPTEN__) || defined(_WIN32))
# include <sched.h>
#endif
-#if defined(_WIN32)
-# include <windows.h>
-
-# include <thread>
-#endif
namespace ov {
namespace threading {
@@ -23,7 +19,7 @@ namespace threading {
#if (defined(__APPLE__) || defined(__EMSCRIPTEN__))
using cpu_set_t = void;
#elif defined(_WIN32)
-using cpu_set_t = DWORD_PTR;
+using cpu_set_t = uintptr_t;
#endif
/**
@@ -60,9 +56,31 @@ using CpuSet = std::unique_ptr<cpu_set_t, ReleaseProcessMaskDeleter>;
#endif
/**
- * @brief Get the cores affinity mask for the current process
+ * @brief Query the cores affinity mask for the current process via system calls.
+ * This is a stateless primitive that reads the process-level affinity mask directly.
+ * On Linux it maps to sched_getaffinity(getpid(), ...); on Windows to
+ * GetProcessAffinityMask(GetCurrentProcess(), ...).
+ * @ingroup ov_dev_api_threading
+ * @return A core affinity mask and the number of CPUs
+ */
+std::tuple<CpuSet, int> query_process_mask();
+
+/**
+ * @brief Query the cores affinity mask of the calling thread via system calls.
+ * This is a stateless primitive that reads the thread-level affinity mask directly.
+ * On Linux it maps to sched_getaffinity(0, ...); on Windows to GetThreadGroupAffinity(...).
+ * @ingroup ov_dev_api_threading
+ * @return A core affinity mask and the number of CPUs
+ */
+std::tuple<CpuSet, int> query_thread_mask();
+
+/**
+ * @brief Get the cores affinity mask for the current process.
+ * Returns a copy of the process baseline mask snapshotted once during CPU topology
+ * initialization (before any thread is pinned), so it stays unpolluted by transient
+ * thread affinity restrictions.
* @ingroup ov_dev_api_threading
- * @return A core affinity mask
+ * @return A core affinity mask and the number of CPUs
*/
std::tuple<CpuSet, int> get_process_mask();
@@ -101,5 +119,37 @@ bool pin_current_thread_by_mask(int ncores, const CpuSet& processMask);
* @return `True` in case of success, `false` otherwise
*/
bool pin_current_thread_to_socket(int socket);
+
+/**
+ * @brief An RAII guard that pins the calling thread to a set of cores and accurately
+ * restores the calling thread's own affinity mask on destruction (including during
+ * stack unwinding on exception).
+ * @ingroup ov_dev_api_threading
+ *
+ * The mask is snapshotted on construction via query_thread_mask() and restored in the
+ * destructor via pin_current_thread_by_mask() if a valid mask was captured.
+ */
+class ScopedThreadAffinity {
+public:
+ ScopedThreadAffinity() {
+ std::tie(_mask, _ncpus) = query_thread_mask();
+ }
+
+ ~ScopedThreadAffinity() {
+ if (_mask) {
+ pin_current_thread_by_mask(_ncpus, _mask);
+ }
+ }
+
+ ScopedThreadAffinity(const ScopedThreadAffinity&) = delete;
+ ScopedThreadAffinity& operator=(const ScopedThreadAffinity&) = delete;
+
+ ScopedThreadAffinity(ScopedThreadAffinity&&) = delete;
+ ScopedThreadAffinity& operator=(ScopedThreadAffinity&&) = delete;
+
+private:
+ CpuSet _mask;
+ int _ncpus = 0;
+};
} // namespace threading
} // namespace ov
diff --git a/src/inference/src/os/cpu_map_info.hpp b/src/inference/src/os/cpu_map_info.hpp
index 889de15e6d2..cefadeeba8e 100644
--- a/src/inference/src/os/cpu_map_info.hpp
+++ b/src/inference/src/os/cpu_map_info.hpp
@@ -13,6 +13,7 @@
#include <vector>
#include "dev/threading/parallel_custom_arena.hpp"
+#include "dev/threading/thread_affinity.hpp"
#include "openvino/util/log.hpp"
namespace ov {
@@ -67,6 +68,27 @@ public:
std::map<int, int> _numaid_mapping_table;
std::mutex _cpu_mutex;
int _socket_idx = 0;
+
+ /**
+ * @brief Return the process affinity mask baseline snapshotted during CPU topology
+ * initialization (before any thread is pinned).
+ * @return The raw process affinity mask baseline
+ */
+ const ov::threading::CpuSet& get_process_mask_raw() const {
+ return _process_mask;
+ }
+
+ /**
+ * @brief Return the number of CPUs associated with the process affinity mask baseline.
+ * @return The number of CPUs
+ */
+ int get_process_mask_ncpus() const {
+ return _process_mask_ncpus;
+ }
+
+private:
+ ov::threading::CpuSet _process_mask;
+ int _process_mask_ncpus = 0;
};
CPU& cpu_info();
diff --git a/src/inference/src/os/lin/lin_system_conf.cpp b/src/inference/src/os/lin/lin_system_conf.cpp
index 4d70df6e2a2..a1958f8e224 100644
--- a/src/inference/src/os/lin/lin_system_conf.cpp
+++ b/src/inference/src/os/lin/lin_system_conf.cpp
@@ -24,6 +24,10 @@ CPU::CPU() {
std::vector<std::vector<std::string>> system_info_table;
std::vector<std::string> node_info_table;
+ // Snapshot the process affinity baseline before any thread is pinned. This keeps the
+ // baseline unpolluted by transient thread affinity restrictions (e.g. getpid()==TID).
+ std::tie(_process_mask, _process_mask_ncpus) = ov::threading::query_process_mask();
+
constexpr int cache_info_mode = 1;
constexpr int freq_info_mode = 2;
@@ -149,9 +153,9 @@ CPU::CPU() {
};
auto check_valid_cpu = [&]() {
- ov::threading::CpuSet mask;
- int ncpus = 0;
- std::tie(mask, ncpus) = ov::threading::get_process_mask();
+ // Use the process affinity baseline snapshotted at the start of the constructor directly,
+ // avoiding re-entry into cpu_info() while the singleton is being constructed.
+ const ov::threading::CpuSet& mask = _process_mask;
if ((_processors == 0) || mask == nullptr) {
return -1;
diff --git a/src/inference/src/os/win/win_system_conf.cpp b/src/inference/src/os/win/win_system_conf.cpp
index 629dc0f7aba..5c5806032e3 100644
--- a/src/inference/src/os/win/win_system_conf.cpp
+++ b/src/inference/src/os/win/win_system_conf.cpp
@@ -12,12 +12,16 @@
#include <vector>
#include "dev/threading/parallel_custom_arena.hpp"
+#include "dev/threading/thread_affinity.hpp"
#include "openvino/runtime/system_conf.hpp"
#include "os/cpu_map_info.hpp"
namespace ov {
CPU::CPU() {
+ // Snapshot the process affinity baseline before any thread is pinned.
+ std::tie(_process_mask, _process_mask_ncpus) = ov::threading::query_process_mask();
+
DWORD len = 0;
if (GetLogicalProcessorInformationEx(RelationAll, nullptr, &len) || GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
return;
diff --git a/src/inference/src/system_conf.cpp b/src/inference/src/system_conf.cpp
index e720809c3d4..d3e21ff3734 100644
--- a/src/inference/src/system_conf.cpp
+++ b/src/inference/src/system_conf.cpp
@@ -45,6 +45,10 @@
# include <sys/types.h>
#endif
+#if defined(_WIN32)
+# include <windows.h>
+#endif
+
#if defined(OPENVINO_ARCH_X86) || defined(OPENVINO_ARCH_X86_64)
# define XBYAK_NO_OP_NAMES
# define XBYAK_UNDEF_JNL
diff --git a/src/inference/tests/unit/CMakeLists.txt b/src/inference/tests/unit/CMakeLists.txt
index aedb02bc048..bad6934b004 100644
--- a/src/inference/tests/unit/CMakeLists.txt
+++ b/src/inference/tests/unit/CMakeLists.txt
@@ -41,6 +41,7 @@ ov_add_test_target(
${CMAKE_CURRENT_SOURCE_DIR}/property_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/query_model_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/single_file_storage.cpp
+ ${CMAKE_CURRENT_SOURCE_DIR}/thread_affinity_test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/tlv_format.cpp
${CMAKE_CURRENT_SOURCE_DIR}/variable_state_test.cpp
DEPENDENCIES
diff --git a/src/inference/tests/unit/thread_affinity_test.cpp b/src/inference/tests/unit/thread_affinity_test.cpp
new file mode 100644
index 00000000000..742d0d58ce9
--- /dev/null
+++ b/src/inference/tests/unit/thread_affinity_test.cpp
@@ -0,0 +1,317 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "dev/threading/thread_affinity.hpp"
+
+#include <gtest/gtest.h>
+
+#include <bitset>
+#include <memory>
+#include <stdexcept>
+#include <tuple>
+#include <vector>
+
+#if defined(_WIN32)
+# include <windows.h>
+#endif
+
+namespace {
+
+#if defined(__linux__) || defined(_WIN32)
+
+// Regression test for the process-affinity baseline cache: get_process_mask() must return the
+// unpolluted process baseline even if the calling thread's affinity is temporarily restricted
+// (Linux maps getpid() to the main thread TID, so a plain sched_getaffinity(getpid(),...) from a
+// pinned thread would return the thread's narrow mask).
+TEST(ThreadAffinity, ProcessMaskStaysAtBaselineWhileThreadIsPinned) {
+ auto baseline = ov::threading::get_process_mask();
+ auto& baseline_mask = std::get<0>(baseline);
+ const int baseline_ncpus = std::get<1>(baseline);
+ ASSERT_NE(baseline_mask, nullptr);
+# if defined(__linux__)
+ ASSERT_GT(baseline_ncpus, 0);
+ const size_t size = CPU_ALLOC_SIZE(baseline_ncpus);
+
+ // Requires at least two CPUs to distinguish the narrowed thread mask from the baseline.
+ if (CPU_COUNT_S(size, baseline_mask.get()) < 2) {
+ GTEST_SKIP() << "Process has fewer than 2 CPUs available; test not applicable.";
+ }
+
+ ov::threading::ScopedThreadAffinity restore;
+
+ // Pick a single CPU to restrict the current thread to.
+ int target_cpu = -1;
+ for (int i = 0; i < baseline_ncpus; i++) {
+ if (CPU_ISSET_S(i, size, baseline_mask.get())) {
+ target_cpu = i;
+ break;
+ }
+ }
+ ASSERT_GE(target_cpu, 0);
+
+ ov::threading::CpuSet narrow{CPU_ALLOC(baseline_ncpus)};
+ ASSERT_NE(narrow, nullptr);
+ CPU_ZERO_S(size, narrow.get());
+ CPU_SET_S(target_cpu, size, narrow.get());
+
+ // Pin the calling thread to a single CPU.
+ ASSERT_TRUE(ov::threading::pin_current_thread_by_mask(baseline_ncpus, narrow));
+
+ // query_thread_mask() must now reflect the restricted (narrow) mask.
+ auto thread_mask = ov::threading::query_thread_mask();
+ auto& thread_mask_ptr = std::get<0>(thread_mask);
+ ASSERT_NE(thread_mask_ptr, nullptr);
+ ASSERT_EQ(CPU_COUNT_S(size, thread_mask_ptr.get()), 1);
+ ASSERT_TRUE(CPU_ISSET_S(target_cpu, size, thread_mask_ptr.get()));
+
+ // get_process_mask() must still return the full baseline, not the narrowed thread mask.
+ auto baseline_after = ov::threading::get_process_mask();
+ auto& baseline_after_mask = std::get<0>(baseline_after);
+ ASSERT_NE(baseline_after_mask, nullptr);
+ ASSERT_TRUE(CPU_EQUAL_S(size, baseline_after_mask.get(), baseline_mask.get()));
+ // The baseline must contain the restricted CPU as well (it is a superset).
+ ASSERT_TRUE(CPU_ISSET_S(target_cpu, size, baseline_after_mask.get()));
+# elif defined(_WIN32)
+ // Requires at least two CPUs to distinguish the narrowed thread mask from the baseline.
+ if (std::bitset<sizeof(DWORD_PTR) * 8>(*baseline_mask).count() < 2) {
+ GTEST_SKIP() << "Process has fewer than 2 CPUs available; test not applicable.";
+ }
+
+ ov::threading::ScopedThreadAffinity restore;
+
+ // Pick a single CPU to restrict the current thread to.
+ int target_cpu = -1;
+ for (int i = 0; i < static_cast<int>(sizeof(DWORD_PTR) * 8); i++) {
+ if ((*baseline_mask & (DWORD_PTR(1) << i)) != 0) {
+ target_cpu = i;
+ break;
+ }
+ }
+ ASSERT_GE(target_cpu, 0);
+
+ // Pin the calling thread to a single CPU.
+ ov::threading::CpuSet narrow =
+ std::make_unique<ov::threading::cpu_set_t>(static_cast<ov::threading::cpu_set_t>(DWORD_PTR(1) << target_cpu));
+ ASSERT_NE(narrow, nullptr);
+ ASSERT_TRUE(ov::threading::pin_current_thread_by_mask(0, narrow));
+
+ // query_thread_mask() must now reflect the restricted (narrow) mask.
+ auto thread_mask = ov::threading::query_thread_mask();
+ auto& thread_mask_ptr = std::get<0>(thread_mask);
+ ASSERT_NE(thread_mask_ptr, nullptr);
+ ASSERT_EQ(static_cast<ov::threading::cpu_set_t>(*thread_mask_ptr),
+ static_cast<ov::threading::cpu_set_t>(DWORD_PTR(1) << target_cpu));
+
+ // get_process_mask() must still return the full baseline, not the narrowed thread mask.
+ auto baseline_after = ov::threading::get_process_mask();
+ auto& baseline_after_mask = std::get<0>(baseline_after);
+ ASSERT_NE(baseline_after_mask, nullptr);
+ ASSERT_EQ(static_cast<ov::threading::cpu_set_t>(*baseline_after_mask),
+ static_cast<ov::threading::cpu_set_t>(*baseline_mask));
+ // The baseline must contain the restricted CPU as well (it is a superset).
+ ASSERT_TRUE((*baseline_after_mask & (DWORD_PTR(1) << target_cpu)) != 0);
+# endif // defined(__linux__) || defined(_WIN32)
+}
+
+// Verifies that if an exception is thrown in a block guarded by ScopedThreadAffinity, the calling
+// thread's original affinity mask is accurately restored when the exception is caught.
+TEST(ThreadAffinity, ScopedThreadAffinityRestoresOnException) {
+# if defined(__linux__)
+ const int ncpus = std::get<1>(ov::threading::query_thread_mask());
+ ASSERT_GT(ncpus, 0);
+ const size_t size = CPU_ALLOC_SIZE(ncpus);
+ const auto before = ov::threading::query_thread_mask();
+ ASSERT_NE(std::get<0>(before), nullptr);
+
+ try {
+ ov::threading::ScopedThreadAffinity guard;
+
+ // Restrict the thread to the first available CPU.
+ int target_cpu = -1;
+ for (int i = 0; i < ncpus; i++) {
+ if (CPU_ISSET_S(i, size, std::get<0>(before).get())) {
+ target_cpu = i;
+ break;
+ }
+ }
+ ASSERT_GE(target_cpu, 0);
+ ov::threading::CpuSet narrow{CPU_ALLOC(ncpus)};
+ CPU_ZERO_S(size, narrow.get());
+ CPU_SET_S(target_cpu, size, narrow.get());
+ ASSERT_TRUE(ov::threading::pin_current_thread_by_mask(ncpus, narrow));
+
+ // Confirm the thread is now pinned to a single CPU, then throw.
+ auto pinned = ov::threading::query_thread_mask();
+ ASSERT_EQ(CPU_COUNT_S(size, std::get<0>(pinned).get()), 1);
+ throw std::runtime_error("boom");
+ } catch (const std::runtime_error&) {
+ }
+
+ // The guard's destructor must have restored the original mask during unwinding.
+ auto after = ov::threading::query_thread_mask();
+ ASSERT_NE(std::get<0>(after), nullptr);
+ ASSERT_TRUE(CPU_EQUAL_S(size, std::get<0>(after).get(), std::get<0>(before).get()));
+# elif defined(_WIN32)
+ const auto before = ov::threading::query_thread_mask();
+ ASSERT_NE(std::get<0>(before), nullptr);
+
+ try {
+ ov::threading::ScopedThreadAffinity guard;
+
+ // Restrict the thread to the first available CPU.
+ int target_cpu = -1;
+ for (int i = 0; i < static_cast<int>(sizeof(DWORD_PTR) * 8); i++) {
+ if ((*std::get<0>(before) & (DWORD_PTR(1) << i)) != 0) {
+ target_cpu = i;
+ break;
+ }
+ }
+ ASSERT_GE(target_cpu, 0);
+ ov::threading::CpuSet narrow = std::make_unique<ov::threading::cpu_set_t>(
+ static_cast<ov::threading::cpu_set_t>(DWORD_PTR(1) << target_cpu));
+ ASSERT_TRUE(ov::threading::pin_current_thread_by_mask(0, narrow));
+
+ // Confirm the thread is now pinned to a single CPU, then throw.
+ auto pinned = ov::threading::query_thread_mask();
+ ASSERT_EQ(*std::get<0>(pinned), static_cast<ov::threading::cpu_set_t>(DWORD_PTR(1) << target_cpu));
+ throw std::runtime_error("boom");
+ } catch (const std::runtime_error&) {
+ }
+
+ // The guard's destructor must have restored the original mask during unwinding.
+ auto after = ov::threading::query_thread_mask();
+ ASSERT_NE(std::get<0>(after), nullptr);
+ ASSERT_EQ(static_cast<ov::threading::cpu_set_t>(*std::get<0>(after)),
+ static_cast<ov::threading::cpu_set_t>(*std::get<0>(before)));
+# endif
+}
+
+// Verifies that nested ScopedThreadAffinity guards restore the calling thread's mask in the correct
+// (reverse) order, so inner guards are restored before outer ones.
+TEST(ThreadAffinity, ScopedThreadAffinityNestedUnwinding) {
+# if defined(__linux__)
+ const int ncpus = std::get<1>(ov::threading::query_thread_mask());
+ ASSERT_GT(ncpus, 0);
+ const size_t size = CPU_ALLOC_SIZE(ncpus);
+ const auto before = ov::threading::query_thread_mask();
+ ASSERT_NE(std::get<0>(before), nullptr);
+ // Requires at least two CPUs for two distinct single-CPU masks.
+ if (CPU_COUNT_S(size, std::get<0>(before).get()) < 2) {
+ GTEST_SKIP() << "Process has fewer than 2 CPUs available; test not applicable.";
+ }
+
+ auto set_mask_of_cpu = [&](int cpu) {
+ ov::threading::CpuSet m{CPU_ALLOC(ncpus)};
+ CPU_ZERO_S(size, m.get());
+ CPU_SET_S(cpu, size, m.get());
+ return ov::threading::pin_current_thread_by_mask(ncpus, m);
+ };
+
+ // Pick two distinct available CPUs.
+ int cpu_a = -1;
+ int cpu_b = -1;
+ for (int i = 0; i < ncpus; i++) {
+ if (!CPU_ISSET_S(i, size, std::get<0>(before).get()))
+ continue;
+ if (cpu_a < 0) {
+ cpu_a = i;
+ } else {
+ cpu_b = i;
+ break;
+ }
+ }
+ ASSERT_NE(cpu_a, -1);
+ ASSERT_NE(cpu_b, -1);
+
+ try {
+ ov::threading::ScopedThreadAffinity outer;
+ ASSERT_TRUE(set_mask_of_cpu(cpu_a));
+ {
+ ov::threading::ScopedThreadAffinity inner;
+ ASSERT_TRUE(set_mask_of_cpu(cpu_b));
+
+ // Inner guard must have snapshotted the mask pinned in the outer scope (cpu_a).
+ auto inner_snapshot = ov::threading::query_thread_mask();
+ ASSERT_EQ(CPU_COUNT_S(size, std::get<0>(inner_snapshot).get()), 1);
+ ASSERT_TRUE(CPU_ISSET_S(cpu_b, size, std::get<0>(inner_snapshot).get()));
+ }
+
+ // Close the inner scope normally: the inner guard restores the outer-scope mask (cpu_a).
+ auto inner_restored = ov::threading::query_thread_mask();
+ ASSERT_EQ(CPU_COUNT_S(size, std::get<0>(inner_restored).get()), 1);
+ ASSERT_TRUE(CPU_ISSET_S(cpu_a, size, std::get<0>(inner_restored).get()));
+
+ // Throw inside the outer scope so the outer guard unwinds and restores before-mask.
+ throw std::runtime_error("boom");
+ } catch (const std::runtime_error&) {
+ }
+
+ // After unwinding, the outer guard must have restored the original thread mask.
+ auto after = ov::threading::query_thread_mask();
+ ASSERT_NE(std::get<0>(after), nullptr);
+ ASSERT_TRUE(CPU_EQUAL_S(size, std::get<0>(after).get(), std::get<0>(before).get()));
+# elif defined(_WIN32)
+ const auto before = ov::threading::query_thread_mask();
+ ASSERT_NE(std::get<0>(before), nullptr);
+ // Requires at least two CPUs for two distinct single-CPU masks.
+ if (std::bitset<sizeof(DWORD_PTR) * 8>(*std::get<0>(before)).count() < 2) {
+ GTEST_SKIP() << "Process has fewer than 2 CPUs available; test not applicable.";
+ }
+
+ auto set_mask_of_cpu = [&](int cpu) {
+ ov::threading::CpuSet m =
+ std::make_unique<ov::threading::cpu_set_t>(static_cast<ov::threading::cpu_set_t>(DWORD_PTR(1) << cpu));
+ return ov::threading::pin_current_thread_by_mask(0, m);
+ };
+
+ // Pick two distinct available CPUs.
+ int cpu_a = -1;
+ int cpu_b = -1;
+ for (int i = 0; i < static_cast<int>(sizeof(DWORD_PTR) * 8); i++) {
+ if (!(*std::get<0>(before) & (DWORD_PTR(1) << i)))
+ continue;
+ if (cpu_a < 0) {
+ cpu_a = i;
+ } else {
+ cpu_b = i;
+ break;
+ }
+ }
+ ASSERT_NE(cpu_a, -1);
+ ASSERT_NE(cpu_b, -1);
+
+ try {
+ ov::threading::ScopedThreadAffinity outer;
+ ASSERT_TRUE(set_mask_of_cpu(cpu_a));
+ {
+ ov::threading::ScopedThreadAffinity inner;
+ ASSERT_TRUE(set_mask_of_cpu(cpu_b));
+
+ // Inner guard must have snapshotted the mask pinned in the outer scope (cpu_a).
+ auto inner_snapshot = ov::threading::query_thread_mask();
+ ASSERT_EQ(static_cast<ov::threading::cpu_set_t>(*std::get<0>(inner_snapshot)),
+ static_cast<ov::threading::cpu_set_t>(DWORD_PTR(1) << cpu_b));
+ }
+
+ // Close the inner scope normally: the inner guard restores the outer-scope mask (cpu_a).
+ auto inner_restored = ov::threading::query_thread_mask();
+ ASSERT_EQ(static_cast<ov::threading::cpu_set_t>(*std::get<0>(inner_restored)),
+ static_cast<ov::threading::cpu_set_t>(DWORD_PTR(1) << cpu_a));
+
+ // Throw inside the outer scope so the outer guard unwinds and restores before-mask.
+ throw std::runtime_error("boom");
+ } catch (const std::runtime_error&) {
+ }
+
+ // After unwinding, the outer guard must have restored the original thread mask.
+ auto after = ov::threading::query_thread_mask();
+ ASSERT_NE(std::get<0>(after), nullptr);
+ ASSERT_EQ(static_cast<ov::threading::cpu_set_t>(*std::get<0>(after)),
+ static_cast<ov::threading::cpu_set_t>(*std::get<0>(before)));
+# endif
+}
+
+#endif // defined(__linux__) || defined(_WIN32)
+
+} // namespace