Mac / iPhone:有没有办法在不使用Objective-C的情况下获取线程标识符? [英] Mac/iPhone: Is there a way to get a thread identifier without using Objective-C?
问题描述
有没有办法获得当前正在运行的线程的任何类型的线程标识符,而无需求助于Objective-C的NSThread。
Is there a way to get any kind of thread identifier of the currently running thread without resorting to Objective-C's NSThread.
我正在改进我们的自定义调试跟踪系统正确处理多个线程。对于每行跟踪输出,我想打印一个线程ID或一个线程名称。线程以各种方式实例化,例如,使用NSOperationQueue和pthread函数。
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选项
pthread_t
似乎是特定平台 _opaque_pthread_h
的typedef。现在可以使用 _opaque_pthread_h
的字段,即使它是hack-y而且不可移植。它有一个long类型的 __ sig
字段,但是对于我的进程的所有线程,它似乎具有相同的值。
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选项
[NSThread name]
需要 NSAutoreleasePool
,但我不希望这是一个要求,因为我们的大部分代码都是纯C ++,所以它会是很高兴只是在没有自动释放池包装的情况下启动c ++函数。
[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.
推荐答案
我找到了一种足以获得跟踪输出的唯一标识符的方法。
I found a one way that is enough to get some kind of unique identifier for trace output.
pthread_mach_thread_np
可用于获取线程标识符,iPhone上的unsigned int。
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());
显然,这是NSLog输出中使用的相同线程ID。
Apparently this is a same thread id that is used in NSLog output.
这篇关于Mac / iPhone:有没有办法在不使用Objective-C的情况下获取线程标识符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!