gettid()和pthread_self()的区别

今日OS作业:
gettid()和pthread_self()的区别

查阅了很多资料做了一个小总结(来源于别的文章):

  1. gettid()是linux内核实现的函数,在内核看来任何线程也是一个轻量级进程,从下面内核实现的sys_gettid看来,gettid()返回的是内核管理的轻量级进程的进程id。
  2. pthread_self 得到实际上是线程描述符pthread 指针地址。
  3. gettid()是内核给线程(轻量级进程)分配的进程id,全局(所有进程中)唯一;pthread_self()是在用户态实现的,获取的id实际上是主线程分配给子线程的线程描述符的地址而已,只是在当前进程空间中是唯一的。
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函数等待新线程结束。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值