10

I am having some trouble figuring out how pthread_key_t and pthread_key_create work. From my understand, each thread has TLS (thread local storage) and that a key is used to access the thread local storage. What I do not get is when a key is created, does every thread get to use it? Lets say Thread 0 creates key 0, can Thread 1 then use key 0? If Thread 1 used key 0, would it access its own TLS or Thread 0's TLS?

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

Alexey Kukanov
  • 12,479
  • 2
  • 36
  • 55
user972276
  • 2,973
  • 9
  • 33
  • 46
  • 1
    For newcomers, I suggest reading Chapter *31: Threads: Thread Safety and Per-Thread Storage* of the *The Linux Programming Interface* book, you will get all your answers there. – Rick Apr 17 '19 at 08:52

1 Answers1

9

pthread_keys are just what you said, thread local storage referred to by a common key. So multiple threads use the same key, but get different storage space (per thread).

A quick example (contrived too), say you were building an asynchronous server (like IMAP). You could keep track of client connections in an array, with each having a key for the current task/request. So when a request comes in a new thread is spun up and the thread stores in the Client_Connection->WhatAmIDoing key a pointer to the "request" structure. The thread now wouldn't have to pass around that pointer because any function that thread executes could simply call the pthread_getspecific() function and get the pointer to what it's supposed to be doing.

Chris S
  • 766
  • 4
  • 13
  • 1
    So, looking at the source code for pthread_key_create, it sets a variable, called key, inside the pthread_key_t to whatever is returned form TlsAlloc. Key is a pointer but what is returned from TlsAlloc? is it just an array of empty slots for each thread? Also, if each thread has its own Tls space, does each element in the array just point to the threads Tls space? I am just getting confused somewhere and I dont know where. Maybe I am making this more complex than it needs to be. – user972276 Jan 25 '12 at 19:06
  • 3
    Well technically yes, the pthread_key is just a pointer to a sparse array, which is created when you call the _create function. When a thread calls the _setspecific() function it fills in a entry in the array with the thread's ID and the value stored by the function (in my example a pointer to a struct). When a thread calls _getspecific() it looks up the array by the key, then the entry in that array by the thread ID, to find the stored value. – Chris S Jan 25 '12 at 19:13
  • 1
    Do remember the point of these interfaces is to abstract what's going on behind the scenes so your program isn't dependent on the platform/implementation. – Chris S Jan 25 '12 at 19:16