获取线程ID比获取pthread_self或gettid更好的方法

时间:2011-06-19 12:27:25

标签: linux pthreads

我的问题是,是否有一个函数返回 pthread_self gettid 以外的线程ID。 pthread_self 的问题在于它返回一个地址,而 gettid 则返回系统范围的全局tid。我想要相对的线程ID,所以线程ID应该是0,1,2,3等,而不是 pthread_self 的地址。

1 个答案:

答案 0 :(得分:4)

没有。如果你真的需要它(我怀疑),实现你自己的机制。

  • 声明全球static int thread_count;
  • 声明全球static __thread int my_thread_id;
  • 当线程启动时,锁定互斥锁并分配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等)(这是标准的)。