I want to maintain some thread-specific data using pthread_key_t.
Thus, I made following structure to record pthread_key_t for each
pthread_t:
struct {
pthread_t thread;
pthread_key_t key;
} thinfo[MAX_ENTRY];
Later, to retrive right key for the given thread, I made
following function:
pthread_key_t *
get_thread_key(pthread_t thread)
{
int i;
for (i = 0; i < MAX_ENTRY; i++) {
if (pthread_equal(thread, thinfo.thread) == 0)
return &thinfo.key;
}
return NULL;
}
First question: Is it safe to call pthread_equal() with an
uninitialized thread_t argument?
If a thread is terminated, one entry in `thinfo' table should be
marked invalid. If pthread_t were a pointer to an opaque type, I
would set it to NULL, but pthread_t is not a pointer type, so I have
not a clear solution so far.
Second question: Is there any way to distinguish valid pthread_t value
against invalid pthread_t value? Or, is there any way for
pthread_key_t type?
If not, I'm afraid that I need to add a predicate member into `thinfo'
table like this:
struct {
pthread_t thread;
pthread_t_key_t key;
int valid; /* nonzero if `thread' is a valid ID */
} thinfo[MAX_ENTRY];
And:
pthread_key_t *
get_thread_key(pthread_t thread)
{
int i;
for (i = 0; i < MAX_ENTRY; i++) {
if (thinfo.valid && (pthread_equal(thread, thinfo.thread) == 0))
return &thinfo.key;
}
return NULL;
}
Thanks in advance.
Oops, I completely misunderstood the mechanism of pthread_key_create
().
For my purpose, I need only one key, not each key per thread.
Please, ignore the source code of my original question.
However, I still wonder if there is a way to mark invalid state into
pthread_t
or pthread_key_t value.
> Please, ignore the source code of my original question.
> However, I still wonder if there is a way to mark invalid state into
> pthread_t
> or pthread_key_t value.
There are two ways:
1) Keep a 'valid' flag along with the pthread_t.
2) Create a thread that will never use this chunk of code. Use its id
as the 'invalid' pthread_t.
DS