Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I assign my own "thread names" in Xcode?

Xcode's "thread list" pane shows English-like names for several special threads: com.apple.main-thread, com.apple.libdispatch-manager, com.dispatchfractal.opencl, com.dispatchfractal.opengl, com.apple.root.low-priority,... But for user-created threads that field is just blank.

Is there any way to set that "thread name" field programmatically from my application? For example, if I've got a thread devoted to network I/O, I'd like it to show up as "com.example.network-io" in the debugger; if I spawn five worker threads I'd like to be able to name them "worker A", "worker B", etc. Does Xcode pull its thread-names from some API that I could hook into myself? Maybe something like CFAssignDebuggerNameToCurrentThread? :)

enter image description here

like image 760
Quuxplusone Avatar asked Sep 24 '12 17:09

Quuxplusone


2 Answers

I use the following code in Swift 5 to rename the current thread:

    pthread_setname_np("myThreadName")
like image 69
j.s.com Avatar answered Oct 15 '22 13:10

j.s.com


If you can get a reference to the thread whose name you want to change, you can change it in the debugger console. Two ways to do that for the current thread:

  • (lldb) po [[NSThread currentThread] setName:@"foo"]

  • (lldb) expression (void)[(NSThread*)[NSThread currentThread] setName:@"foo"];

I'd guess you could do the same from a breakpoint that has an associated expression. If you have a method that you know will run in the thread that you're interested in, you could set a breakpoint containing one of the above commands and have it automatically continue after running the command. That'd have the effect of automatically setting the name of the thread every time you run the code, which might be handy for debugging.

like image 39
Caleb Avatar answered Oct 15 '22 14:10

Caleb