可以使用 gettid得到:
#include <pthread.h>
#include <sys/types.h>
void * threadEntry(void * arg)
{
printf("thread %d: ID: %d\n", (int)arg, gettid());
return arg;
}
int main(void)
{
pthread_t threads[4];
int i;
for(i = 0; i < 4; i++)
{
pthread_create(threads+i, NULL, threadEntry, (void *)i);
}
for(i = 0; i < 4; i++)
{
pthread_join(threads[i], NULL);
}
return 0;
}
但编译的时候报错:
(.text+0x7): undefined reference to `gettid'
用man 查了下,发现:
Glibc does not provide a wrapper for this system call; call it using syscall(2).
原来是,GLIBC没有实现这样的函数,所以要直接调用系统调用的接口了
于是改成如下的代码:
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/syscall.h>
#define gettid() syscall(__NR_gettid)
void * threadEntry(void * arg)
{
printf("thread %d: ID: %d\n", (int)arg, gettid());
return arg;
}
int main(void)
{
pthread_t threads[4];
int i;
for(i = 0; i < 4; i++)
{
pthread_create(threads+i, NULL, threadEntry, (void *)i);
}
for(i = 0; i < 4; i++)
{
pthread_join(threads[i], NULL);
}
return 0;
}
syscall(__NR_gettid) 也可以写为 syscall(SYS_gettid)
这是因为, <bits/syscall.h> 里面做了如下的定义:
#define SYS_gettid __NR_gettid
__NR_gettid 在 <asm/unistd.h>里面定义为:
#define __NR_gettid 224