簡體   English   中英

獲取 MacOS 上當前進程產生的活動線程數

[英]Get number of active threads spawned by current process on MacOS

我一直在網上和通過系統標頭搜索過去 3 個小時,但在 C/C++ 中找不到我想在 MacOS 上執行的操作的可用機制。

我正在尋找一種方法來檢索當前正在運行的進程的活動/活動線程總數。 我承認,如果我計算我自己產生的線程,這將是微不足道的,但事實並非如此。 我正在處理的代碼庫使用了多個線程庫,我需要這些基本信息來進行調試。

在 linux 上,我只能訪問/proc/self/stat/ ,其中第 20 個元素是活動線程的總數,但這在 MacOS 上不可用。 如果有幫助,這必須在 MacOS 12.0 + 上工作

有人有什么想法嗎?

通過一些谷歌搜索,在我看來,在從task_for_pid()獲得正確的 mach 端口后,您應該能夠使用task_threads()獲取此信息:

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 上的工作原理,但您可以查看這些其他帖子:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM