0
点赞
收藏
分享

微信扫一扫

Linux编程:pthread_self与gettid获得线程id

天行五煞 2022-04-21 阅读 97
linux

pthread_self返回的是POSIX phtread库在用户空间标识的线程id,与linux调度任务没有关系,且只能保证同一进程在同一时间的线程具有不同的id,换句话说就是同一进程在不同时间先后运行的线程可能具有相同的id:

#include <iostream>
#include <pthread.h>
#include <thread>

using namespace std;

void t_func(void *arg)
{
    cout << "This is thread:" << *(int*)arg << ", pthread_self id:"<< pthread_self() <<endl;
}

int main()
{
    int i = 1;
    thread t1(t_func, &i);
    t1.join();
    ++i;
    thread t2(t_func, &i);
    t2.join();   
    return 0; 
}

运行程序输出:
This is thread:1, pthread_self id:139920145725184
This is thread:2, pthread_self id:139920145725184

可见先后运行的两个线程具有相同的pthread_self id

gettid需要用户自己在封装一下,不过他是通过系统调用获得的linux调度任务id(内核线程id):

#include <iostream>
#include <pthread.h>
#include <thread>
#include <unistd.h>
#include <sys/syscall.h>

using namespace std;

pid_t gettid()    //需要封装一下系统调用
{
    return syscall(SYS_gettid);
} 

void t_func(void *arg)
{
    cout << "This is thread:" << *(int*)arg << ", gettid id:"<< gettid() <<endl;
    sleep(10);
}

int main()
{
    int i = 1;
    cout << "pid:" << getpid() << endl;
    thread t1(t_func, &i);
    t1.join();
    ++i;
    thread t2(t_func, &i);
    t2.join();   
    return 0; 
}

运行程序输出:
pid:228298
This is thread:1, gettid id:228299
This is thread:2, gettid id:228302

运行时刻,通过ps -efL | grep t_thread 查看:
UID    PID     PPID    LWP     C    NLWP STIME TTY      TIME      CMD
user   228298  201990  228298  0    2    00:14 pts/0    00:00:00 ./t_thread
user   228298  201990  228299  0    2    00:14 pts/0    00:00:00 ./t_thread
user   228298  201990  228302  0    2    00:14 pts/0    00:00:00 ./t_thread

可见通过这种方式获得的线程id:228299与228302,是可以在linux的调度任务中查询到的内核线程id
举报

相关推荐

0 条评论