how to get thread id of a pthread in linux c program?

后端 未结 11 831
忘了有多久
忘了有多久 2020-12-02 07:05

In linux c program, how to print thread id of a thread created by pthread library?
for ex: we can get pid of a process by getpid()

11条回答
  •  孤街浪徒
    2020-12-02 07:35

    As noted in other answers, pthreads does not define a platform-independent way to retrieve an integral thread ID.

    On Linux systems, you can get thread ID thus:

    #include 
    pid_t tid = gettid();
    

    On many BSD-based platforms, this answer https://stackoverflow.com/a/21206357/316487 gives a non-portable way.

    However, if the reason you think you need a thread ID is to know whether you're running on the same or different thread to another thread you control, you might find some utility in this approach

    static pthread_t threadA;
    
    // On thread A...
    threadA = pthread_self();
    
    // On thread B...
    pthread_t threadB = pthread_self();
    if (pthread_equal(threadA, threadB)) printf("Thread B is same as thread A.\n");
    else printf("Thread B is NOT same as thread A.\n");
    

    If you just need to know if you're on the main thread, there are additional ways, documented in answers to this question how can I tell if pthread_self is the main (first) thread in the process?.

提交回复
热议问题