gettid 和pthread_self的区别

本文探讨了Linux中gettid系统调用与pthread_self函数的区别,指出gettid返回的是内核层面的线程ID,而pthread_self返回的是POSIX线程ID。通过代码示例展示了如何使用这两个函数,并对比了它们的输出。

gettid 和pthread_self的区别

The man page for gettid says:


The thread ID returned by this call is not the same thing as a POSIX thread ID
(i.e., the opaque value returned by pthread_self(3)).

看来,线程的id,在linux中分为POSIX thread ID , 和内核中对每一个线程的id.

gettid是linux 的一个系统调用, 查看sys_gettid
/* Thread ID - the internal kernel "pid" */
asmlinkage long sys_gettid(void)
{
return task_pid_vnr(current);
}


struct upid {
/* Try to keep pid_chain in the same cacheline as nr for find_pid */
int nr;
struct pid_namespace *ns;
struct hlist_node pid_chain;
};

struct pid
{
atomic_t count;
/* lists of tasks that use this pid */
struct hlist_head tasks[PIDTYPE_MAX];
struct rcu_head rcu;
int level;
struct upid numbers[1];
};


这里面的level不清楚是什么含义? 有知道的告诉我,多谢了。




问:_syscall[0-6]跑哪里去了
答:没有了

问:那现在用啥呢?
答:用系统调用 syscall(2),第一个参数是SYS_name,后面参数照写






# define _GNU_SOURCE
# include < stdio. h>
# include < sys/ types. h>
# include < pthread. h>
# include < stdlib. h>
# include < string . h>
# include < unistd. h>
# include < linux/ unistd. h>
# include < sys/ syscall. h>

void * thsf( void * arg )
{
pthread_t th;
char * retstr;
retstr= malloc ( 50) ;
memset ( retstr, 0, 50) ;


strcpy ( retstr, "New thread quit!" ) ;


th= pthread_self( ) ;
# if 1
printf ( "New thread,pid:%d,tid:%x,another tid:%x./n" ,
getpid( ) ,
th,
( long ) syscall( SYS_gettid) ) ;
# endif

pthread_exit ( retstr) ;
}

int main( )
{
pthread_t nth1, mth, oth;
void * a;
if ( pthread_create ( & nth1, NULL , thsf, NULL ) )
printf ( "Error create new thread./n" ) ;
mth= pthread_self( ) ;

printf ( "Main thread,pid:%d,tid:%x,another tid:%x./n" , getpid( ) , mth, ( long ) syscall( SYS_gettid) ) ;
if ( ! pthread_join ( nth1, & a) )
{
printf ( "New thread quit,message from new thread:%s./n" , ( char * ) a) ;
free ( ( char * ) a) ;
}
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值