我的问题是,是否有一个函数返回 pthread_self 和 gettid 以外的线程ID。 pthread_self 的问题在于它返回一个地址,而 gettid 则返回系统范围的全局tid。我想要相对的线程ID,所以线程ID应该是0,1,2,3等,而不是 pthread_self 的地址。
答案 0 :(得分:4)
没有。如果你真的需要它(我怀疑),实现你自己的机制。
static int thread_count;
static __thread int my_thread_id;
以下是一个例子:
static int thread_count;
static __thread int my_thread_id;
static pthread_mutex_t start_mtx = PTHREAD_MUTEX_INITIALIZER;
static void *th_function(void *arg)
{
pthread_mutex_lock(&start_mtx);
my_thread_id = thread_count++;
pthread_mutex_unlock(&start_mtx);
/* rest of function */
}
显然你也可以使用特定于线程的数据(pthread_setspecific
等)(这是标准的)。