获取 MacOS 上当前进程生成的活动线程数

问题描述 投票:0回答:2

过去 3 个小时我一直在网上和系统头文件中搜索,但找不到 C/C++ 中可用的机制来实现我在 MacOS 上尝试执行的操作。

我正在寻找一种方法来检索当前正在运行的进程的活动/活动线程总数。我承认,如果我计算我自己生成的线程,这将是微不足道的,但事实并非如此。我正在处理的代码库使用多个线程库,我需要这些基本信息用于调试目的。

在 Linux 上,我可以访问

/proc/self/stat/
,其中第 20 个元素是活动线程的总数,但这在 MacOS 上不可用。如果有帮助,这必须在 MacOS 12.0 + 上运行

有人有什么想法吗?

c++ c multithreading macos operating-system
2个回答
4
投票

通过谷歌搜索,在我看来,在从

task_threads()
获得正确的马赫端口后,您应该能够使用
task_for_pid()
获取此信息:

int pid = 123; // PID you want to inspect
mach_port_t me = mach_task_self();
mach_port_t task;
kern_return_t res;
thread_array_t threads;
mach_msg_type_number_t n_threads;

res = task_for_pid(me, pid, &task);
if (res != KERN_SUCCESS) {
    // Handle error...
}

res = task_threads(task, &threads, &n_threads);
if (res != KERN_SUCCESS) {
    // Handle error...
}

// You now have `n_threads` as well as the `threads` array
// You can use these to extract info about each thread

res = vm_deallocate(me, (vm_address_t)threads, n_threads * sizeof(*threads));
if (res != KERN_SUCCESS) {
    // Handle error...
}

但请注意,

task_for_pid()
的使用可能会受到限制。我不太了解 macOS 上的权利如何运作,但您可以查看这些其他帖子:


0
投票

Marco Bonelli 答案的简化(C++)版本。
如果对当前进程的线程感兴趣,可以跳过

task_for_pid

   #include <mach/mach.h>

   int getCurrentThreadCount()
   {
       auto me = mach_task_self();
       thread_array_t threads;
       mach_msg_type_number_t numberOfThreads;

       auto res = task_threads(me, &threads, &numberOfThreads);
       if (res != KERN_SUCCESS) {
           return -1;
       }

       res = vm_deallocate(me, (vm_address_t)threads, numberOfThreads * sizeof(*threads));
       if (res != KERN_SUCCESS) {
           return -1;
       }

       return numberOfThreads;
   }
© www.soinside.com 2019 - 2024. All rights reserved.