2013-03-14 28 views
11

Thread name Example: 'com.apple.coremedia.player.async'检索线程名称在非当前线程的IOS

如何检索线程的“名称”?

(请参阅应用程序暂停的xcode图片,其中,我所称的“名称”以黄色突出显示,“com.apple.coremedia.player.async”...我可以检索正在运行的线程,并且曾尝试以下,没有运气

mach_msg_type_number_t count, i; 
thread_act_array_t list; 

task_threads(mach_task_self(), &list, &count); 
for (i = 0; i < count; i++) { 
    if (list[i] == mach_thread_self()) continue; 

    char theName[16]; 

    memset(theName, 0x00, sizeof(theName)); 
    pthread_getname_np(list[i], theName); 
    printf("The thread name is %s.\n", theName); 

} 

注意:我不要求当前线程的线程名。我很感兴趣,从集运行的线程获得线程名(见上面的例子) ..所以有关[NSThread currentThread]的解决方案将不起作用

+1

我相信PLCrashReporter是能够做到这一点,尝试检查他们的专页。 – borrrden 2013-03-14 04:47:08

+0

你究竟想通过这样做完成什么? – eyebrowsoffire 2013-03-14 05:59:51

+0

打印出每个正在运行的线程的线程名称 – user353877 2013-03-14 06:05:00

回答

15

问题很简单:task_threads返回Mach端口的数组,而不是pthread_t的数组。在您致电pthread_getname_np时,您正在将Mach端口视为pthread_t。但是Mach端口不是pthread_t。您需要将每个转换为使用pthread_from_mach_thread_np一个pthread_t:从我的测试程序

static void dumpThreads(void) { 
    char name[256]; 
    mach_msg_type_number_t count; 
    thread_act_array_t list; 
    task_threads(mach_task_self(), &list, &count); 
    for (int i = 0; i < count; ++i) { 
     pthread_t pt = pthread_from_mach_thread_np(list[i]); 
     if (pt) { 
      name[0] = '\0'; 
      int rc = pthread_getname_np(pt, name, sizeof name); 
      NSLog(@"mach thread %u: getname returned %d: %s", list[i], rc, name); 
     } else { 
      NSLog(@"mach thread %u: no pthread found", list[i]); 
     } 
    } 
} 

输出:

2013-03-14 03:21:45.908 hole[28315:c07] url connection complete 
2013-03-14 03:21:46.787 hole[28315:c07] mach thread 3079: getname returned 0: 
2013-03-14 03:21:46.789 hole[28315:c07] mach thread 6147: getname returned 0: 
2013-03-14 03:21:46.790 hole[28315:c07] mach thread 6915: getname returned 0: 
2013-03-14 03:21:46.792 hole[28315:c07] mach thread 7683: getname returned 0: WebThread 
2013-03-14 03:21:46.794 hole[28315:c07] mach thread 13059: getname returned 0: com.apple.NSURLConnectionLoader 
2013-03-14 03:21:46.796 hole[28315:c07] mach thread 16131: getname returned 0: 
2013-03-14 03:21:46.798 hole[28315:c07] mach thread 17667: getname returned 0: 
2013-03-14 03:21:46.801 hole[28315:c07] mach thread 18187: getname returned 0: com.apple.CFSocket.private 
2013-03-14 03:21:46.802 hole[28315:c07] mach thread 20227: getname returned 0: 
+0

你先生太棒了!感谢您花时间回答我的问题。社区感谢您的服务=) – user353877 2013-03-14 09:14:47

+0

如果线程名称是由某人设置的,这项工作很适合我。如果线程是分派工作线程可以很好地找出正在该线程上执行的分派队列的名称。项目https://github.com/kstenerud/KSCrash有函数ksmach_getThreadName和ksmach_getThreadQueueName,但它们在OSX 10.9上不适用于我。 – 2014-01-09 12:36:39

9
+0

很好的答案,所以+1 – 2013-03-14 04:56:08

+7

请注意,如果OP只需要当前线程,此答案只会有所帮助。如果OP想要所有线程,那么这个答案是没有用的。 – borrrden 2013-03-14 05:18:00

+0

如何通过列表(而不是当前线程)获得线程名称,如上例task_threads(mach_task_self(),&list,&count); – user353877 2013-03-14 05:34:20