开发者

A better way to get thread ID than pthread_self or gettid

开发者 https://www.devze.com 2023-03-14 03:20 出处:网络
My question is if there is a开发者_C百科 function which returns thread ID other than pthread_self and gettid. The problem with pthread_self is that it returns an address while gettid returns system wi

My question is if there is a开发者_C百科 function which returns thread ID other than pthread_self and gettid. The problem with pthread_self is that it returns an address while gettid returns system wide global tid. I want relative thread id, so thread ids should be 0, 1, 2, 3, etc and not addresses as in case of pthread_self.


There isn't. If you really need it (which I doubt), implement your own mechanism.

  • Declare a global static int thread_count;
  • Declare a global static __thread int my_thread_id;
  • When a thread starts, lock a mutex and assign the id

Here's an example:

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 */
}

Obviously you could also use thread-specific data (pthread_setspecific etc) (which is standard).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号