How to count number of alive threads in iOS

ios, multithreading, objective-c

Solution

Michael Dautermann already answered the question, but this is an example to get threads count using Mach API. Note that its work only on simulator (tested with iOS 6.1), running it on device will fail because `task_for_pid` return `KERN_FAILURE`.

/**
 * @return -1 on error, else the number of threads for the current process
 */
static int getThreadsCount()
{
    thread_array_t threadList;
    mach_msg_type_number_t threadCount;
    task_t task;

    kern_return_t kernReturn = task_for_pid(mach_task_self(), getpid(), &task);
    if (kernReturn != KERN_SUCCESS) {
        return -1;
    }

    kernReturn = task_threads(task, &threadList, &threadCount);
    if (kernReturn != KERN_SUCCESS) {
        return -1;
    }
    vm_deallocate (mach_task_self(), (vm_address_t)threadList, threadCount * sizeof(thread_act_t));

    return threadCount;
}

Problem

I want to get the number of threads which are 'alive' in my iOS application. Can I use `threadDictionary` in the `NSThread` class? Or can I use `mach/thread_info.h`?

Original source

Related problems