How do I get a thread ID from an arbitrary pthread_t?

前端 未结 5 631
轮回少年
轮回少年 2020-11-27 16:13

I have a pthread_t, and I\'d like to change its CPU affinity. The problem is that I\'m using glibc 2.3.2, which doesn\'t have pthread_setaffinity_np(). That\'s OK, though, b

相关标签:
5条回答
  • 2020-11-27 16:34

    Actually pthread_self returns 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;
    }
    
    0 讨论(0)
  • 2020-11-27 16:34

    In glibc 2.24 the pthread_t returned is just the pointer to an opaque struct pthread. You can look up the definition in nptl/descr.h.

    0 讨论(0)
  • 2020-11-27 16:35
    pthread_t pthread_self()
    

    this return current pthread_t, which is thread id, you can convert it to type "unsigned int",

    0 讨论(0)
  • 2020-11-27 16:40

    Since pthreads do not need to be implemented with Linux threads (or kernel threads at all, for that matter), and some implementations are entirely user-level or mixed, the pthreads interface does not provide functions to access these implementation details, as those would not be portable (even across pthreads implementations on Linux). Thread libraries that use those could provide this as an extension, but there do not seem to be any that do.

    Other than accessing internal data structures of the threading library (which you understandably do not want, although with your assumptions about processor affinity and Linux thread IDs, your code will not be portable anyway), you may be able to play a trick at creation time, if you control the code that creates the threads:

    Give pthread_create() an entry function that calls gettid() (which by the way you are likely to have to do using the syscall macro directly because it is not always exported by libc), stores the result somewhere, and then calls the original entry function. If you have multiple threads with the same entry function, you can pass an incremented pointer into an array in the arg argument to pthread_create, which will then be passed to the entry function you created to store the thread ID in. Store the pthread_t return value of pthread_create in the same order, and then you will be able to look up the Linux thread IDs of all threads you created given their pthread_t value.

    Whether this trick is worth it, depends on how important setting the CPU affinity is in your case, versus not accessing internal structures of the thread library or depending on a thread library that provides pthread_setaffinity_np.

    0 讨论(0)
  • 2020-11-27 16:40

    I would suggest a simple workaround with a shared int array where you could write the thread id from the threads to access it later.

    Hope that helps.

    0 讨论(0)
提交回复
热议问题