Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mac/iPhone: Is there a way to get a thread identifier without using Objective-C?

Is there a way to get any kind of thread identifier of the currently running thread without resorting to Objective-C's NSThread.

I'm improving our custom debug tracing system to handle multiple threads properly. For each line of trace output, I'd like to print a thread id or a thread name. Threads are instantiated in various ways, e.g. both NSOperationQueue and pthread functions are used.

I've currently a following two alternatives, but I'm not satisfied with either of them. Are there any other options?

pthread_t option

pthread_t seems to be a typedef of a platform specific _opaque_pthread_h. It would be ok to use fields of _opaque_pthread_h for now, even if it's hack-y and not portable. It has a __sig field of type long, but that seems to have a same value for all threads of my process.

NSThread option

[NSThread name] requires NSAutoreleasePool to be in place, but I don't want that to be a requirement as most of our code is pure C++, so it would be nice to just to launch c++ function without autorelease pool wrapping.

like image 547
Teemu Kurppa Avatar asked Oct 08 '09 21:10

Teemu Kurppa


People also ask

What is the thread ID?

Thread Id is a long positive integer that is created when the thread was created. During the entire lifecycle of a thread, the thread ID is unique and remains unchanged. It can be reused when the thread is terminated.

What is thread in Objective C?

A thread is a sequence of instructions that can be executed by a runtime. Each process has at least one thread.


2 Answers

I found a one way that is enough to get some kind of unique identifier for trace output.

pthread_mach_thread_np can be used to get a thread identifier, an unsigned int on iPhone.

mach_port_t tid = pthread_mach_thread_np(pthread_self());

Apparently this is a same thread id that is used in NSLog output.

like image 99
Teemu Kurppa Avatar answered Sep 28 '22 11:09

Teemu Kurppa


I appreciate this is a pretty old question.

To get the same Thread ID that is reported in macOS's Console.app I used:

uint64_t tid;
pthread_threadid_np(NULL, &tid);
printf("%#08x\nr", (unsigned int) tid);

A screenshot from Console.app on macOS.

enter image description here

like image 22
rustyMagnet Avatar answered Sep 28 '22 09:09

rustyMagnet