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

后端 未结 11 688
忘了有多久
忘了有多久 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:55

    There is also another way of getting thread id. While creating threads with

    int pthread_create(pthread_t * thread, const pthread_attr_t * attr, void * (*start_routine)(void *), void *arg);

    function call; the first parameter pthread_t * thread is actually a thread id (that is an unsigned long int defined in bits/pthreadtypes.h). Also, the last argument void *arg is the argument that is passed to void * (*start_routine) function to be threaded.

    You can create a structure to pass multiple arguments and send a pointer to a structure.

    typedef struct thread_info {
        pthread_t thread;
        //...
    } thread_info;
    //...
    tinfo = malloc(sizeof(thread_info) * NUMBER_OF_THREADS);
    //...
    pthread_create (&tinfo[i].thread, NULL, handler, (void*)&tinfo[i]);
    //...
    void *handler(void *targs) {
        thread_info *tinfo = targs;
        // here you get the thread id with tinfo->thread
    }
    

提交回复
热议问题