简体   繁体   中英

Thread Id differs in main() and start_routine() - Pthread

#include <pthread.h>
#include <stdio.h>

void* printHello (void* threadId)
{
    pthread_t *my_tid = (pthread_t *)threadId;
    printf ("\nIn `printHello ()`: thread id %ld", (long)*my_tid);
    pthread_exit (NULL);
}

int main ()
{
    pthread_t        arrayOfThreadId [5];
    int                  returnValue;
    unsigned int iterate;

    for (iterate = 0; iterate < 5; iterate++)
    {
        if (returnValue = pthread_create (&arrayOfThreadId [iterate],
                                    NULL,
                                    printHello,
                                    (void*) &arrayOfThreadId [iterate]) != 0)
        {
            printf ("\nerror: pthread_create failed with error number %d", returnValue);
        }
        else
        {
            printf ("\nIn `main()`: creating thread %ld", arrayOfThreadId [iterate]);
        }
    }

    printf ("\nBefore `return 0;` in `main()`");
    pthread_exit (NULL);
    return 0;
}

Output:

In 

`main()`: creating thread 139683073914640
In `main()`: creating thread 139683065521936
In `main()`: creating thread 139683057129232
In `main()`: creating thread 139683048736528
In `main()`: creating thread 139683040343824
Before `return 0;` in `main()`
In `printHello ()`: thread id 140735115959408
In `printHello ()`: thread id 4195680
In `printHello ()`: thread id 0
In `printHello ()`: thread id 0
In `printHello ()`: thread id 139683073914640

Why do the threadIDs differ?

I missing some point here. I have done accidentally wrong, it seems.

You're passing the address of your threadId, but you're casting that address to a pthread_t, thus treating the address of an element in your arrayOfThreadId as if it were a pthread_t.

Do this instead:

void* printHello (void* threadId)
{
    pthread_t *my_tid = threadId;
    printf ("\nIn `printHello ()`: thread id %ld\n", (long)*my_tid);

And make sure your main() does not exit until all the threads are finished, else you risk having the array destroyed before the threads pokes into it.

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