简体   繁体   中英

Implementing pthread_self() in C

I'm trying to implement pthread_self() in C but I'm confused on what exactly it does. I'm aware that it returns the thread ID but is that ID a memory location because it returns a pthread_t which I'm not sure how to interpret. Additionally, how would I go about retrieving the id of the thread, do I just create a new thread and return it?

pthread_self() returns the ID of the thread. Please check man pages for pthread_self and pthread_create.

man 3 pthread_self
man 3 pthread_create

For pthread_create(), the first argument is of type pthread_t. It is assigned the ID of the newly created thread. This ID is used to identify the thread for other pthread functions. The abstract type of pthread_t is implementation dependent.

Before returning, a successful call to pthread_create() stores the ID of the new thread in the buffer pointed to by thread; this identifier is used to refer to the thread in subsequent calls to other pthread functions.

pthread_self returns the same ID, what pthread_create stores in the first argument "thread"

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

In my system pthread_t type is "unsigned long int"

/usr/include/x86_64-linux-gnu/bits/pthreadtypes.h:typedef unsigned long int pthread_t;

In the following example, the value returned by pthread_self() and th1 are same.

// main function:
    pthread_t th1;

    if(rc1 = pthread_create(&th1, NULL, &functionC1, NULL))
    {
           printf("Thread creation failed, return code %d, errno %d", rc1, errno);
    }
    printf("Printing thread id %lu\n", th1);

// Thread function: 
    void *functionC1(void *)
    {
            printf("In thread function Printing thread id %lu\n", pthread_self());
    }

    Output:
    Printing thread id 140429554910976
    In thread function Printing thread id 140429554910976

Please check blog Tech Easy for more information on threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM