Linux C代码获取线程ID

gettid系统调用用于获取线程ID,但在glibc中未封装,需直接使用syscall。pthread_self返回的线程ID由线程库分配,两者在进程内唯一但不相同。gettid返回的线程ID可被系统命令如top显示,而pthread_self的ID则不行。

Linux C代码获取线程ID

gettid可以获取线程id,但是通过man gettid可以看到下面这两句

在这里插入图片描述

也就是说glibc没有为这个gettid封装系统调用,需要使用syscall

       #define _GNU_SOURCE
       #include <unistd.h>
       #include <sys/syscall.h>
       #include <sys/types.h>

      pid_t  tid = syscall(SYS_gettid);

具体通过上面的代码就可以的到线程ID

调用这个函数返回的线程id,与POSIX thread ID(通过调用pthread_self的结果不是同一个东西)。

下面我们再通过man pthread_self看看关于它的描述

在这里插入图片描述

线程ID 保证仅在进程中是唯一的。 在连接已终止的线程或已分离的线程已终止后,可以重用线程 ID

这里也说明pthread_self获取的线程ID只保证在进程中是唯一的,不同的进程中的线程ID有可能是不同的。

pthread_self得到的也就是POSIX thread ID,它是由线程库实现来负责分配和维护,gettid()返回的线程ID是一个有内核分配的数字,类似进程ID.

pthread_self得到的线程ID是不同通过系统命令查看的,比如top命令,这些看到的线程ID都是通过gettid得到的。

Linux系统上,获取C代码中当前线程的名称通常涉及到使用`pthread`库提供的功能。`pthread_self()`函数可以返回当前线程ID,然后通过`pthread_get_name_np()`函数配合线程名称数组(如果有预先设置),可以得到线程名称。以下是一个简单的示例: ```c #include <stdio.h> #include <pthread.h> // 定义线程名称数组 const char* thread_names[] = { "Thread 0", "Thread 1", "Thread 2", /* 添加更多的线程名称 */ }; void *thread_function(void *arg) { pthread_t self_thread_id; char name[64]; size_t len; // 获取当前线程ID if (pthread_equal(pthread_self(), arg)) { self_thread_id = arg; // 如果传入的是主线程(NULL),则等于self } else { self_thread_id = pthread_self(); } // 获取线程名称 if (pthread_getname_np(self_thread_id, name, sizeof(name), &len) == 0) { printf("Current thread ID: %lu, Name: %s\n", (unsigned long)self_thread_id, name); } else { perror("Failed to get thread name"); } return NULL; } int main() { pthread_t threads[NUM_THREADS]; // 创建并启动线程 for (size_t i = 0; i < NUM_THREADS; ++i) { if (pthread_create(&threads[i], NULL, thread_function, i != 0 ? threads[i - 1] : NULL) != 0) { perror("Failed to create thread"); return 1; } } // 等待所有线程结束 for (size_t i = 0; i < NUM_THREADS; ++i) { if (pthread_join(threads[i], NULL) != 0) { perror("Failed to join thread"); } } return 0; } ``` 在这个例子中,你需要预先为每个线程设置一个名称,并确保它们在`thread_names`数组中。如果线程未指定名称,那么`pthread_get_name_np()`将返回默认值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值