pthread_self()獲取當選線程的ID。
這個ID與pthread_create的第一個參數返回的相同。
但是與ps命令看到的不同,因此只能用於程序內部,用於對線程進行操作。
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <unistd.h> 4 #include <pthread.h> 5 6 void* fun(void* p) 7 { 8 printf("child thread id=%lu\n",pthread_self());//獲取當前線程ID 9 //sleep(100); 10 return NULL; 11 } 12 13 int main(int argc,char* argv[]) 14 { 15 pthread_t tid; 16 printf("main thread id=%lu\n",pthread_self());//獲取當前線程ID 17 pthread_create(&tid,NULL,fun,NULL); 18 printf("child's tid=%lu\n",tid); 19 sleep(100); //wait child 20 return 0; 21 }
編譯運行一下,觀察輸出,這個ID與pthread_create的第一個參數返回的相同
$ gcc threadid.c -lpthread $ ./a.out main thread id=3069878272 child's tid=3068613728 child thread id=3068613728
但是與ps看到的結果是不同的,不是一回事(我去掉了無關輸出)
$ ps -efL|grep a.out UID PID PPID LWP C NLWP STIME TTY TIME CMD ubuntu 17693 17387 17693 0 2 17:06 pts/4 00:00:00 ./a.out ubuntu 17693 17387 17694 0 2 17:06 pts/4 00:00:00 ./a.out
