开发者

How to get pid from pthread

in RH Linux, every pthread is mapping to a pid, which can be monitored in tools suc开发者_StackOverflow中文版h as htop. but how can i get the pid of a thread? getpid() just return the pid of the main thread.


There are two thread values that get confused. pthread_self() will return the POSIX thread id; gettid() will return the OS thread id. The latter is linux specific and not guaranteed to be portable but probably what you are really looking for.

EDIT As PlasmaHH notes, gettid() is called via syscall(). From the syscall() man page:

   #define _GNU_SOURCE
   #include <unistd.h>
   #include <sys/syscall.h>
   #include <sys/types.h>

   int
   main(int argc, char *argv[])
   {
       pid_t tid;

       tid = syscall(SYS_gettid);
   }


pthread_self();

Can be called to return the ID of the calling thread.

Also PID is process Id, A thread has thread Id not PID. All threads running in the same process will have the same PID.


A PID is a Process ID, not a thread ID. Threads running on the same process will obviously all be associated with the same PID.

Because pthreads tries to be portable you cannot obtain the ID of the underlying OS thread directly. It's even possible that there isn't an underlying OS thread.


pthread_self does not get the tid. it proviedes a handle or pointer of type pthread_t for usage in pthread functions.

see here for an example what a real world program might return:

http://www.c-plusplus.de/forum/212807-full


Actually pthread_self return pthread_t and not a integer thread id you can work with, the following helper function will get you that in a portable way across different POSIX systems.

uint64_t gettid() {
    pthread_t ptid = pthread_self();
    uint64_t threadId = 0;
    memcpy(&threadId, &ptid, std::min(sizeof(threadId), sizeof(ptid)));
    return threadId;
}


Threads have tids (threadIds), and all threads run in the same process (pid). So, your threads should all have the same pid assuming they're created in the same process, bu they'll have different tids.

pthread_self() gives tid, and getpid() gets the pid.


I think the function you are looking for is pthread_self

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜