我想获得iOS应用程序中“活着”的线程数。
我可以在threadDictionary
课程中使用NSThread
吗?或者我可以使用mach/thread_info.h
吗?
答案 0 :(得分:5)
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;
}
答案 1 :(得分:4)
这个也适用于设备:
#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);
答案 2 :(得分:3)
"threadDictionary
"是有关特定 NSThread的信息。这不是线程的总数。
如果您想跟踪您创建的“NSThread
”对象,您可能需要创建自己的NSMutableArray并向其添加新的NSThread对象,并确保对象有效且正确(即线程正在执行,线程已完成或取消等等。每次你想要计算你的NSThreads。
由于NSThread与threads created and/or references via Grand Central Dispatch (GCD)或其他类型的线程(例如pthreads)不同,这可能仍然无法满足您的需求。