Counting threads
You learn something new every day. (If that’s not true, it’s time to change jobs.) Today, among other things, I learned that calling the Mach task_threads API on the current task returns a list of threads that must be deallocated with mach_port_deallocate to avoid leaking Mach ports (and therefore to avoid leaking wired memory).
In other words, if you’re using Mach APIs to count the number of threads currently running in the current process, this is the correct way to avoid leaking memory:
unsigned int numThreads;
thread_array_t threads;
kern_return_t result;
int i;
result = task_threads(mach_task_self(), &threads, &numThreads);
if (result == KERN_SUCCESS) {
for(i = 0; i < numThreads; i++) {
mach_port_deallocate(mach_task_self(), threads[i]);
}
vm_deallocate(mach_task_self(), (vm_offset_t) threads,
numThreads * sizeof(thread_t));
printf("Number of threads: %u\n", numThreads);
}