我的问题是是否有一个函数返回 pthread_self 和 gettid 以外的线程 ID。 pthread_self 的问题在于它返回一个地址,而 gettid 返回系统范围的全局 tid。我想要相对线程 ID,因此线程 ID 应该是 0、1、2、3 等,而不是像 pthread_self 那样的地址。
最佳答案
没有。如果您确实需要它(我对此表示怀疑),请实现您自己的机制。
- 声明一个全局的
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
等)(这是标准的)。
关于linux - 比 pthread_self 或 gettid 更好的获取线程 ID 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6402352/