我想在我的iOS应用程序中获取"活着"的线程数。
我可以在NSThread
类中使用threadDictionary
吗?还是可以使用mach/thread_info.h
?
Michael Dautermann已经回答了这个问题,但这是使用MACH API获得线程计数的示例。 Note 仅在模拟器上工作(使用iOS 6.1测试),在设备上运行它会失败,因为task_for_pid
返回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;
}
这个设备也可以在设备上工作:
#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);
" threadDictionary
"是有关特定 nsthread的信息。这不是线程的总数。
如果要跟踪您创建的" NSThread
"对象,则可能需要创建自己的NSMutableArray并在其上添加新的NSThread对象,并确保对象有效且正确(即线程正在执行,线程已完成或取消等。
这可能仍然不会给您您想要的东西,因为NSthread与通过Grand Central Dispatch(GCD)或其他类型的线程或其他类型的线程(例如Pthreads)的线程不同和/或引用。
。