如何在MacOS 12.0+下获取当前进程的活跃线程数?
在MacOS 12.0+上获取当前进程活跃线程总数的C/C++实现方案
针对你无法通过线程库统计、且Linux /proc 机制不适用的场景,以下两种MacOS原生方案可直接从系统层面获取准确的活跃线程总数,适配12.0及以上版本:
方法1:使用sysctl系统调用
通过内核提供的sysctl接口查询进程信息,无需依赖第三方库:
#include <sys/types.h> #include <sys/sysctl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> int get_current_process_thread_count() { int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()}; size_t size = 0; // 获取缓冲区大小 if (sysctl(mib, sizeof(mib)/sizeof(mib[0]), NULL, &size, NULL, 0) == -1) { perror("sysctl get size failed"); return -1; } struct kinfo_proc *proc_info = (struct kinfo_proc*)malloc(size); if (!proc_info) { perror("malloc failed"); return -1; } // 获取进程详情 if (sysctl(mib, sizeof(mib)/sizeof(mib[0]), proc_info, &size, NULL, 0) == -1) { perror("sysctl get proc info failed"); free(proc_info); return -1; } int thread_count = proc_info->kp_proc.p_nthreads; free(proc_info); return thread_count; } int main() { int count = get_current_process_thread_count(); if (count != -1) { printf("当前进程活跃线程总数:%d\n", count); } return 0; }
编译命令:clang thread_count.c -o thread_count
方法2:使用libproc库的proc_pidinfo函数
通过MacOS自带的libproc库简化查询流程,代码更简洁:
#include <libproc.h> #include <stdio.h> #include <unistd.h> int get_current_process_thread_count() { struct proc_taskinfo task_info; pid_t pid = getpid(); int ret = proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &task_info, sizeof(task_info)); if (ret != sizeof(task_info)) { perror("proc_pidinfo failed"); return -1; } return task_info.pti_threadnum; } int main() { int count = get_current_process_thread_count(); if (count != -1) { printf("当前进程活跃线程总数:%d\n", count); } return 0; }
编译命令:clang thread_count.c -o thread_count -lproc
以上两种方案均绕过线程库差异,直接从内核获取进程的线程统计数据,完全满足调试场景的需求。
内容的提问来源于stack exchange,提问作者Yattabyte
相关产品推荐
相关产品推荐

