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

标签 linux pthreads

我的问题是是否有一个函数返回 pthread_selfgettid 以外的线程 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/

相关文章:

linux - Tesseract 批量将图像转换为可搜索的 PDF 和多个相应的文本文件

linux - 自动 ftp crc 长度错误后 gunzip

ruby - TestFirst.org Learn Ruby rake 和弃用警告 :should and :expect syntax

c - 线程不会在 C 中执行

c - 使用 C 中的线程从命令行反转字符串 - 段错误

multithreading - 编译时-pthread和-lpthread之间的区别

linux - 未在原始套接字上接收到正确的数据

linux - 仅当尚未添加值时才使用 bash 将值添加到数组

c - 我在使用线程传递参数时遇到问题

C - 使用互斥锁同步多个线程