Search code examples
c++cmultithreadingmacosoperating-system

Get number of active threads spawned by current process on MacOS


I've been searching for the last 3 hours online and through system headers, but can not find a mechanism available to me in C/C++ for what I'm trying to do on MacOS.

I'm looking to find a way to retrieve for the currently running process the total number of active/alive threads. I acknowledge that this would be trivial if I were counting threads that I myself spawn, but this is not the case. The code base I'm working on uses several threading libraries, and I require this basic information for debugging purposes.

On linux I can just acces /proc/self/stat/ where the 20th element is the total number of alive threads, but this is not available on MacOS. If it helps, this has to work on MacOS 12.0 +

Does anyone have any ideas?


Solution

  • From a bit of googling around, it seems to me like you should be able to obtain this information using task_threads(), after getting the right mach port from 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...
    }
    

    Note however that the usage of task_for_pid() might be restricted. I don't know much about how entitlements work on macOS, but you can check these other posts: