Linux下如何使用gettid函数且和pthread_self()的区别

gettid

在这里插入图片描述
它被定义在<sys./types.h>头文件中,但在程序中使用时发现没有gettid函数。

  • 我们可以自己封装一下
#include<sys/syscall.h>
syscall(SYS_gettid); //该函数和gettid等价。


在编写程序时可以使用上述函数。也可以将其封装一下。
pid_t gettid()
{
	return syscall(SYS_gettid);
} 

pthread_self()和gettid的区别

先谈谈pthread_self()函数
  • pthread_self()函数是线程库POSIX Phtread实现函数,它返回的线程ID是由线程库封装过然后返回的。既然是线程库函数,那么该函数返回的ID也就只在进程中有意义,与操作系统的任务调度之间无法建立有效关联。
  • 另外glibc的Pthreads实现实际上把pthread_t用作一个结构体指针(它的类型是unsigned long),指向一块动态分配的内存,而且这块内存是反复使用的。这就造成pthread_t的值很容易重复。Pthreads只保证同一进程内,同一时刻的各个线程的id不同;不能保证同一进程先后多个线程具有不同的id。(当前一个线程结束其生命周期,进程又新创建了一个线程,那么该线程ID可能会使用消亡线程的ID)。
#include<iostream>
#include<pthread.h>
#include<thread>

void func(void *arg)
{
    std::cout << "I am " << *(int*)arg << "'s thread" << pthread_self() << "\n";
}

int main()
{
    int i = 1;
    std::thread t1(func, &i);
    t1.join();
    ++i;
    std::thread t2(func, &i);
    t2.join();    
}

运行结果发现前后两个线程ID相同。
在这里插入图片描述

gettid()
  • 该函数就是Linux提供的函数,它返回的ID就是"线程"(轻量级进程)ID,相当于内核线程ID。
#include<iostream>
#include<pthread.h>
#include<thread>
#include<sys/syscall.h>
#include<unistd.h>
#include<sys/types.h>

void func(void *arg)
{
    std::cout << "I am " << *(int*)arg << "'s thread" << pthread_self() << "\n";
    std::cout << syscall(SYS_gettid) << "\n";
}


int main()
{
    int i = 1;
    std::thread t1(func, &i);
    t1.join();
    ++i;
    std::thread t2(func, &i);
    t2.join();    
}

运行结果如下
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值