Technical help with pthread_create_key and other key calls

Kaz Kylheku
Mon Sep 18 17:31:00 GMT 2006

> Mead, Jennifer L wrote:
> Hi C folks,
> > 

[ snip ]
> --------

You should always try to post a complete example that someone can cut,
paste and compile.

>    pthread_t main_thr;
>    pthread_t thr;
>    pthread_attr_t attr;
>    main_thr = pthread_self();
>    p=malloc(2);

Okay, here you have p pointing to two bytes. Or NULL, if that failed. :)

>    p = buffer;void *watch_dir(void *arg)

And here you have leaked that two-byte allocation by assigning to p.
What is this extra syntax? It looks like the declaration of an external
But there is no semicolon.

>    pthread_key_t key;
>    pthread_key_create(&key, NULL);

Creating a key as a local variable seen only by one thread is almost
certainly pointless. The idea is that the key is shared among all the
threads.  Each thread looking at that same key will see its own specific
data which it stored under that key.

This is essentially a mechanism for extending threads with user-defined
attributes. The key serves as the attribute name, and the value
(getspecific/setspecific) is that attribute's value in the calling
thread. In each calling thread, the attribute can have a different
value, which is what "thread specific" means.

So the key is usually stored in some static data structure, or perhaps a
dynamically allocated data structure that all the threads know about.

This isn't really a GCC question; there is a comp.programming.threads
Usenet newsgroup for discussing POSIX (and other) threads.

More information about the Gcc-help mailing list