获得线程的 ID

可以使用 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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值