views:

174

answers:

1

I presumed that a pthread_t remains constant - for a given thread - for its entire life, but my experimentation seems to be proving this assumption false. If the id for a given thread does not remain constant across its life, how can I store a pthread_t so another thread can use pthread_join to block until the thread is finished?

For other reasons it would be useful for me to know how to get a unique identifier for a thread that I can convert back and forth to a pthread_t. Is there a way of doing this?

There is lots of great information out there, but I've had a hard time pinning down useful answers for these questions. I'd appreciate any help/advice I can get!

edit: Also, i'm not sure why, but everything seems to work as expected when adding sleep(1) and sleeping for 1sec at the front of every new thread (within the thread's function). This is probably grasping as straws, but could pthread_t values change momentarily during the start of a new thread or something??

+1  A: 

You cannot rely on a pthread_t being unique, but you can use pthread_equal() to determine whether two thread ids refer to the same thread.

NAME
     pthread_equal -- compare thread IDs

SYNOPSIS
     #include <pthread.h>

     int
     pthread_equal(pthread_t t1, pthread_t t2);

DESCRIPTION
     The pthread_equal() function compares the thread IDs t1 and t2.

RETURN VALUES
     The pthread_equal() function will return non-zero if the thread IDs t1 and t2
     correspond to the same thread. Otherwise, it will return zero.
Beano
Thanks! I think that is basically my problem. A follow-up question though:Can old `pthread_t`'s I've gotten and saved still be used to refer to a particular thread?
Hey, quintus, why don't you accept this answer, and ask a new question for your next attempt at violating the posix standard?
Rhythmic Fistman
@fistman: What do you mean violating the posix standard? It's somehow against the rules to want a uniquely identifying number when dealing with threads?? @Beano: Your solution is helpful, but my problem isn't solved. pthread_equal didn't change anything. I think pthread_equal is used because the pthread_t is sometimes a structure, not because multiple numbers correlate to the same thread! Any thoughts?...
I pthread_t from functions pthread_create() and pthread_self() can be used to refer to a particular thread for the lifetime of the thread. pthread_t should be treated as an opaque value that can only be compared with pthread_equal().
Beano
I was able to solve this problem by associating a unique key of my own to pthread_t objects through a map container and using pthread_equal() to find the correct pthread_t when that was needed. Thanks everyone!