pthread 名字设置及ID获取
pthread_setname_np
-
函数原型:
int pthread_setname_np(pthread_t thread, const char *name);
- thread:要设置名称的线程标识符(pthread_t)。
- name:要设置的线程名称(以字符串形式表示)。
-
将指定线程的名称修改为给定的字符串。
-
在调试和线程跟踪时非常有用,可以更方便地识别和追踪不同的线程。
pthread_self
-
函数原型:
pthread_t pthread_self(void);
-
用于获取当前线程的标识符。
示例
-
代码如下:
#define _GNU_SOURCE #include <pthread.h> #include <stdio.h> void* thread_func(void* arg) { pthread_t tid = pthread_self(); printf("Thread id: %lu\n", (unsigned long)tid); return NULL; } int main() { pthread_t tid; pthread_create(&tid, NULL, thread_func, NULL); pthread_setname_np(tid, "thread1"); pthread_join(tid, NULL); return 0; }