プロセスのスレッドidを取得するにはどうすればいいですか?-----gettidとpthreadについてselfの違い


すべては需要から来て、使う必要があるので、言ってください.
 
以前はpthread_を使っていましたselfはスレッドidを取得し、このidは通常臭い臭いが大きい.私を悩ませたのは、すべての資料をめくって、linuxコマンドでスレッドidを取得することができなくて、私はこの邪を信じません.
もちろん、ps-Top pidやtop-HP pidでスレッドidを取得できることも調べましたが、この2つのコマンドを使いましたが、上記のようなスレッドidは取得できませんでした.その後、この2つのコマンドは確かにスレッドidを取得できますが、上記の臭いの大きいidではありません.実は、gettidとpthread_に関連しています.selfの違いです.
gettidはカーネル内の実際のスレッドidを取得し、pthread_selfが取得したのはposixスレッドidで、違います.上記コマンドで取得したスレッドidはgettidに対応しpthread_selfには毛関係はありません.
       pthread_selfは言わないでgettidを見てみましょう.
#include 
#include 
#include 
#include 
#define gettid() syscall(SYS_gettid)
#include 

void* threadFunc(void* p)
{
    printf("threadFunc is %d
", gettid()); int i = 0; while (1) { sleep(1); } return NULL; } int main () { printf("main thread id is %d
", gettid()); pthread_t id; pthread_create (&id, NULL, threadFunc, NULL); pthread_create (&id, NULL, threadFunc, NULL); pthread_create (&id, NULL, threadFunc, NULL); pthread_create (&id, NULL, threadFunc, NULL); pthread_create (&id, NULL, threadFunc, NULL); pthread_create (&id, NULL, threadFunc, NULL); int i = 0; while (1) { sleep(1); } return 0; }

コンパイル:g++test.cpp -lpthread
実行して、次を確認します.
ubuntu@VM-0-15-ubuntu:~$ ps -aux |grep a.out
ubuntu   26810  0.0  0.0  55692   696 pts/3    Sl+  20:12   0:00 ./a.out
ubuntu   26908  0.0  0.1  13228   972 pts/4    S+   20:13   0:00 grep a.out
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ ps -Tp 26810
  PID  SPID TTY          TIME CMD
26810 26810 pts/3    00:00:00 a.out
26810 26811 pts/3    00:00:00 a.out
26810 26812 pts/3    00:00:00 a.out
26810 26813 pts/3    00:00:00 a.out
26810 26814 pts/3    00:00:00 a.out
26810 26815 pts/3    00:00:00 a.out
26810 26816 pts/3    00:00:00 a.out
ubuntu@VM-0-15-ubuntu:~$ 

メインスレッド+6サブスレッドが表示されますか.2番目の列はスレッドid.プロセスidとプライマリスレッドidが等しい.
 
ここで、複数のa.outプロセスを迅速に起動し、プロセスidが隣接していると、スレッドidが重なるのではないかという疑問があります.
私は4つのa.outプロセスをすばやく開き、見てみましょう.
ubuntu@VM-0-15-ubuntu:~$ ps -aux | grep a.out 
ubuntu   27224  0.0  0.0  55692   752 pts/6    Sl+  20:18   0:00 ./a.out
ubuntu   27232  0.0  0.0  55692   700 pts/5    Sl+  20:18   0:00 ./a.out
ubuntu   27239  0.0  0.0  55692   692 pts/4    Sl+  20:18   0:00 ./a.out
ubuntu   27247  0.0  0.0  55692   692 pts/3    Sl+  20:18   0:00 ./a.out

プロセスidが隣接していないことがわかり、スレッドidに隙間を残していて、少し面白いです.
 
最後に、プロセスのスレッドidは必ず上記のように連続しているのでしょうか.
もちろん必ずしも!