2013-03-14 70 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