Reputation: 27360
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
? :)
Upvotes: 12
Views: 5062
Reputation: 1478
I use the following code in Swift 5 to rename the current thread:
pthread_setname_np("myThreadName")
Upvotes: 3
Reputation: 507
pesudo code for -[NSThread setName:]
- (void) setName:(NSString*)thname {
if (self == [NSThread currentThread])
{
pthread_setname_np([thname UTF8String]);
}
else { ... }
...
}
So, the easist way to set name is calling pthread_setname_np.
Upvotes: 1
Reputation: 170859
Probably not exactly what you want but NSThread has setName:
method that allows you to set thread's name, you can attach meaningful name to the thread so you'll get the following in debugger:
[[NSThread mainThread] setName:@"That is main thread!"];
Remember also that some apis (like grand central dispatch) operate with thread pools so you are not guaranteed on what thread your operation will be performed
Edit:
com.apple.main-thread
, com.apple.libdispatch-manager
etc are labels of corresponding dispatch queues. You can set label value when queue is created with dispatch_queue_create
function and later get it from the queue using dispatch_queue_get_label
function.
It seems there's no API to change label value of the existing dispatch queue and I would not advise to change labels of the system queues anyway.
Upvotes: 13
Reputation: 125037
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.
Upvotes: 4