linux下须用sched_getaffinity将亲和性写入cpu_set_t结构体,返回值仅为调用结果;windows用getprocessaffinitymask获取整数掩码,注意位图含义与超线程影响;跨平台应封装为cpu索引集合而非统一整数掩码。

Linux下用 sched_getaffinity 读取当前线程的CPU亲和性掩码
Linux不直接暴露“亲和性屏蔽位”为一个整数,而是通过 cpu_set_t 结构体传递。调用 sched_getaffinity 是唯一标准方式,它把当前线程(或指定PID)实际生效的CPU集合写入该结构体。
常见错误是误以为返回值就是掩码整数——其实返回值是系统调用结果(0成功,-1失败),真正数据在传入的 cpu_set_t* 缓冲区里:
#include <sched.h>
#include <stdio.h>
#include <unistd.h>
cpu_set_t mask;
CPU_ZERO(&mask);
if (sched_getaffinity(0, sizeof(mask), &mask) == 0) {
for (int i = 0; i
<ul>
<li>
<code>CPU_SETSIZE</code> 通常为1024,但实际可用CPU数可能更小,建议配合 <code>sysconf(_SC_NPROCESSORS_ONLN)</code> 校验</li>
<li>若程序未显式设置过亲和性,返回的是继承自父进程(通常是全核)的掩码,不是“系统默认”硬编码值</li>
<li>注意 <code>sizeof(mask)</code> 必须准确;用错大小会导致读越界或截断,<code>sched_getaffinity</code> 可能静默失败</li>
</ul>
<h3>Windows下用 <code>GetProcessAffinityMask</code> 获取进程级掩码</h3>
<p>Windows区分进程级和线程级亲和性,但大多数场景下关心的是进程掩码,对应API是 <code>GetProcessAffinityMask</code>。它返回两个 <code>DWORD_PTR</code>:第一个是进程允许运行的CPU掩码,第二个是系统可用CPU掩码(即“硬上限”)。</p>
<p>关键点在于:返回的掩码是低位有效、按物理CPU编号排列的位图,但Windows可能启用逻辑处理器超线程,此时第0位未必对应物理核心0:</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/gongju/2823" title="C++14"><img
src="https://img.php.cn/upload/manual/001/431/639/6ac8b33c327c4749.png" alt="C++14" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/gongju/2823" title="C++14" class="overflowclass">C++14</a>
<p class="overflowclass">C++14 对 C++11 的修正与增强版本,适合旧系统维护和较老工具链兼容。</p>
</div>
<a rel="nofollow" href="/xiazai/gongju/2823" title="C++14" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<pre class="brush:php;toolbar:false;">#include <windows.h>
#include <iostream>
DWORD_PTR proc_mask, sys_mask;
if (GetProcessAffinityMask(GetCurrentProcess(), &proc_mask, &sys_mask)) {
std::cout
<ul>
<li>若返回 <code>false</code>,需用 <code>GetLastError()</code> 判断原因,常见是权限不足(如被调试器或组策略限制)</li>
<li>64位程序中 <code>DWORD_PTR</code> 是64位,但旧版Windows可能只支持低32位;检查 <code>sys_mask</code> 才知真实CPU数量上限</li>
<li>该API不反映线程单独调用 <code>SetThreadAffinityMask</code> 的效果——线程级设置优先于进程级,但 <code>GetProcessAffinityMask</code> 读不到线程级覆盖</li>
</ul>
<h3>跨平台封装时别直接拼整数掩码</h3>
<p>不同系统对“掩码”的定义不一致:Linux的 <code>cpu_set_t</code> 是位数组结构体,Windows返回原生整数,而macOS压根不提供等价接口(仅支持 <code>thread_policy_set</code> 设置,不可读)。强行统一成一个 <code>uint64_t</code> 掩码会掩盖关键差异。</p>
<p>更稳妥的做法是封装为可枚举的CPU索引集合:</p>
<pre class="brush:php;toolbar:false;">// 伪代码示意
std::vector<int> get_allowed_cpus() {
#ifdef _WIN32
DWORD_PTR m; GetProcessAffinityMask(..., &m, ...);
std::vector<int> res;
for (int i = 0; i >= 1) {
if (m & 1) res.push_back(i);
}
return res;
#else
cpu_set_t set; sched_getaffinity(..., &set);
std::vector<int> res;
for (int i = 0; i
<ul>
<li>不要假设最多64核——Linux <code>CPU_SETSIZE</code> 可能更大,Windows在某些服务器版本支持 >64 逻辑处理器,需动态探测</li>
<li>macOS无标准读取接口,<code>host_processor_info</code> 只能查在线状态,无法得知调度限制,此时应明确报错或降级为“全部可用”</li>
<li>多线程环境下,获取结果仅代表调用时刻的快照;若其他线程正在调用 <code>sched_setaffinity</code> 或 <code>SetThreadAffinityMask</code>,结果可能立即过期</li>
</ul>
<h3>为什么 <code>pthread_getaffinity_np</code> 不推荐直接用</h3>
<p>glibc提供了 <code>pthread_getaffinity_np</code>,但它属于GNU扩展(_np = non-portable),且行为与 <code>sched_getaffinity</code> 不完全一致:它操作的是线程对象本身,而 <code>sched_getaffinity</code> 操作的是内核调度实体(task_struct)。在使用线程池或协程库(如libco、Boost.Fiber)时,前者可能返回错误的掩码。</p>
<ul>
<li>POSIX标准不保证线程级亲和性API的存在,依赖 <code>_np</code> 函数会让代码失去可移植性</li>
<li>即使在同一Linux发行版上,musl libc 完全不提供 <code>pthread_getaffinity_np</code>,编译直接失败</li>
<li>真正需要线程粒度控制时,应优先用 <code>sched_getaffinity</code> 配合 <code>pthread_getattr_np</code> 获取线程ID再传入,而非依赖pthread专属接口</li>
</ul>
实际工程中,最易忽略的是:**掩码反映的是“允许运行”的集合,不是“当前正在运行”的CPU**。即使掩码包含所有核,调度器也可能因负载均衡把线程长期固定在某一个核上——读出的掩码只是约束边界,不是实时状态。</int></int></int>C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










