deltaaruna
deltaaruna

Reputation: 538

How to count number of alive threads in iOS

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?

Upvotes: 4

Views: 4895

Answers (3)

Lukasz
Lukasz

Reputation: 19926

This one works on the device as well:

#include <pthread.h>
#include <mach/mach.h>
// ...
thread_act_array_t threads;
mach_msg_type_number_t thread_count = 0;

const task_t    this_task = mach_task_self();
const thread_t  this_thread = mach_thread_self();

// 1. Get a list of all threads (with count):
kern_return_t kr = task_threads(this_task, &threads, &thread_count);

if (kr != KERN_SUCCESS) {
    printf("error getting threads: %s", mach_error_string(kr));
    return NO;
}

mach_port_deallocate(this_task, this_thread);
vm_deallocate(this_task, (vm_address_t)threads, sizeof(thread_t) * thread_count);

Upvotes: 6

Emmanuel
Emmanuel

Reputation: 2917

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;
}

Upvotes: 7

Michael Dautermann
Michael Dautermann

Reputation: 89569

"threadDictionary" is information about a specific NSThread. It's not the total number of threads.

If you want to keep track of "NSThread" objects you've created, you'll probably need to create your own NSMutableArray and add new NSThread objects to it and make certain the objects are valid and correct (i.e. threads are executing, threads are finished or cancelled, etc.) each time you want to do a count of your NSThreads.

This likely still would not give you exactly what you want because NSThread isn't the same thing as threads created and/or references via Grand Central Dispatch (GCD) or other kinds of threads (e.g. pthreads).

Upvotes: 3

Related Questions