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();    
}

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

pthread_create函数用于创建一个新的线程,其函数原型为: ```c int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg); ``` 其中,参数thread是一个指向pthread_t类型的指针,用于存储新线程的ID;参数attr是一个指向pthread_attr_t类型的指针,用于设置线程的属性,一般为NULL;参数start_routine是一个指向函数的指针,该函数将作为新线程的入口点;参数arg是一个指向void类型的指针,用于传递给start_routine函数的参数。 pthread_self函数用于获取当前线程的ID,其函数原型为: ```c pthread_t pthread_self(void); ``` 下面是一个示例程序,演示了pthread_create函数和pthread_self函数的用法和程序的执行顺序: ```c #include <stdio.h> #include <pthread.h> void *thread_func(void *arg) { pthread_t tid = pthread_self(); printf("New thread created with ID %lu\n", tid); return NULL; } int main() { pthread_t tid; printf("Main thread ID is %lu\n", pthread_self()); pthread_create(&tid, NULL, thread_func, NULL); pthread_join(tid, NULL); return 0; } ``` 程序首先输出了主线程的ID,然后调用pthread_create函数创建了一个新线程,并将其ID存储在tid变量中。pthread_create函数的第三个参数是一个指向函数的指针,该函数将作为新线程的入口点,这里我们传递了thread_func函数的地址。thread_func函数中调用了pthread_self函数获取当前线程的ID,并输出到控制台。最后,主线程调用pthread_join函数等待新线程结束。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值