18

In Windows, it is possible to set the threadname via this code. The threadname is then shown in debuggers.

In MacOSX, I have seen several hints which indicates that there are threadnames. I think the class NSThread also has a name-attribute. My goal is that I can set the threadname in my C++ application and see it in Xcode/gdb.


Other related questions:

Albert
  • 65,406
  • 61
  • 242
  • 386
  • Can I just ask why you accepted the answer you did - it doesn't answer your question but there are others that do? – deanWombourne Sep 12 '11 at 14:37
  • @deanWombourne: At the time of writing, I didn't had MacOSX 10.6. And there were thread names, so the other answer didn't answered that for me. But yea, now this issue is probably outdated. – Albert Sep 12 '11 at 23:48
  • Handy for people who are trying to build stuff for Leopard, though! – SamB Sep 05 '12 at 01:07

2 Answers2

30

I recommend the following:

[[NSThread currentThread] setName:@"My thread name"]; // For Cocoa  
pthread_setname_np("My thread name"); // For GDB.

(You'll need to include pthread.h) Works a treat in XCode 3.2.3 (at least for iPhone development)

Dave H
  • 316
  • 3
  • 3
  • 2
    Meaning no offense to cdespinosa (hi Chris! :), it seems odd to me that his non-answer was accepted. DaveH actually answered the question (and I was able to use his supplied answer to solve MY problem +1 :) – Olie Jun 09 '11 at 15:11
  • Yes, I agree. This sounds like a much better answer. Makes more sense – Henley Aug 30 '11 at 00:23
  • 2
    Btw., `pthread_setname_np` is also available on many other platforms. However, the interface is usually different. See [here](http://stackoverflow.com/a/7989973/133374) for a good overview. – Albert Apr 19 '12 at 13:31
2

Which version of Xcode are you using? Thread names are only supported in Mac OS X 10.6 and Xcode 3.2.

cdespinosa
  • 20,661
  • 6
  • 33
  • 39
  • I am using OSX 10.5 and Xcode 3.1.4. So no chance there? No chance at all in OSX 10.5? In the doc for NSThread:setName, it says available in Mac OS X v10.5 and later. – Albert Jan 13 '10 at 16:37
  • 1
    Yes, but the threadname is not propagated from the Objective-C layer to the runtime threads layer in 10.5, because the pthread_setname_np API doesn't exist until 10.6, and you need Xcode 3.2 to fetch and display the thread name. – cdespinosa Jan 14 '10 at 05:01
  • So, Xcode 3.2 on MacOSX 10.5 would be able to display thread names if I propagate the threadnames to the runtime threads layer? How can I do that? – Albert Jan 15 '10 at 12:06
  • No, Xcode 3.2 is 10.6 only. If you want to see thread names in the Xcode UI, you have to use Xcode 3.2 on Mac OS X 10.6. – cdespinosa Jan 15 '10 at 21:46
  • 3
    Just want to say this explicitely for other readers: pthread_setname_np is the solution. – Albert May 14 '10 at 01:25