pthread_self 简介

来源:互联网 发布:正大数据恢复中心 深圳 编辑:程序博客网 时间:2024/06/05 17:07

NAME

    pthread_self 得到调用线程的ID


SYNOPSIS     
       #include <pthread.h>

       pthread_t pthread_self(void);
       编译链接的时候带上参数-pthread.


DESCRIPTION 
     pthread_self()函数返回调用线程的ID.这个数值与调用 pthread_create 创建本线程时使用的*thread 参数返回的值是一样的。

 

RETURN VALUE     
     这个函数总是成功,返回调用线程的ID。


NOTES  
     Thread IDs 仅仅保证在一个进程内部的唯一性。当一个结束了的线程 joined(使用join等待一个线程结束)之后, 或者一个detached 状态的线程被结束 thread ID可能会被重新使用。 pthread_self()返回的线程ID与 调用 gettid()得到的内核线程ID是不一样的。

 

示例:

#include <pthread.h>   #include <stdlib.h>   #include <stdio.h>   #include <sys/syscall.h>pthread_t ntid;  pid_t gettid(void){  return syscall(__NR_gettid);}void printids(const char *s)  {      pid_t pid;      pthread_t tid;      pid = getpid();      tid = pthread_self();      printf("%s pid is:%u ;tid is :%u (0x%x)\n", s,(unsigned int)pid, (unsigned int)tid, (unsigned int)tid);    printf("%s kid is:%u\n",s,gettid() );}   void *thr_fn(void *arg)  {      printids("new thread: ");      return((void *)0);  }  int main(){int err;    err = pthread_create(&ntid, NULL, thr_fn, NULL);  printf("in main ntid is :%u\n",ntid);    if (err != 0)          printf("can't create thread: %d\n", strerror(err));  printids("main thread:");sleep(3);return 0;}

编译:

$ gcc temp.c -lpthread

运行输出:$ ./a.out

in main ntid is :3078953840
main thread: pid is:2663 ;tid is :3078961968 (0xb7853b30)
main thread: kid is:2663
new thread:  pid is:2663 ;tid is :3078953840 (0xb7851b70)
new thread:  kid is:2664