How does pthread_key_t and pthread_key_create work?

I'm having trouble figuring out how pthread_key_t and pthread_key_create work. As far as I understand, each thread has TLS (local thread storage) and that the key is used to access the local thread storage. What I don't get is when a key is created, does each thread use its use? Suppose Thread 0 creates key 0, can Thread 1 use key 0? If Thread 1 uses key 0, will it access its TLS or TLS Thread 0?

Is there any global array or something that keeps track of all the keys used?

+7
source share
1 answer

pthread_keys is what you said is the local thread store referenced by the shared key. Thus, multiple threads use the same key, but receive different storage space (in the stream).

A quick example (far-fetched too), they say that you built an asynchronous server (for example, IMAP). You can track client connections in the array, each of which has a key for the current task / request. Therefore, when a request arrives in a new stream, it is created, and the stream stores a pointer to the request structure in Client_Connection-> WhatAmIDoing key. Now the thread should not go around this pointer, because any function executed by this thread can simply call the pthread_getspecific () function and get a pointer to what it should do.

+5
source

All Articles