4

What is the difference between declaring a thread-local variable using the dedicated keyword:

_Thread_local int var;

And using the specific tss_ set of functions:

tss_t key;
tss_create(&key, free);
tss_set(key, malloc(sizeof(int)));
int* pVar = tss_get(key);

From what I understand, the _Thread_local keyword declares a variable with thread storage duration, while the tss_ set of functions return a key to the calling thread. This key can then be used to access some global heap memory which can be allocated as needed, and that pointer will only be available to that thread, am I right?

Acorn
  • 24,970
  • 5
  • 40
  • 69
DarkAtom
  • 2,589
  • 1
  • 11
  • 27
  • Given both concepts are largely lifted in their entirety from POSIX/pthreads, I suspect the answer is basically the same as [Thread Specific Data vs Thread Local Storage](https://stackoverflow.com/q/21015738/364696). – ShadowRanger Sep 24 '19 at 19:55
  • Need OS tag to proceed – Joshua Sep 24 '19 at 19:55
  • 1
    @Joshua: The internals might differ by OS, but the API is part of the C11 standard. The OS shouldn't matter for which approach makes sense for the purposes of features. – ShadowRanger Sep 24 '19 at 19:57
  • @ShadowRanger: The answers on your proposed potential duplicate say otherwise (signal handlers). – Joshua Sep 24 '19 at 19:58
  • @Joshua: Signal handler functions have similar limitations regarding `malloc` and the like on all OSes. The old question isn't a duplicate since most of the answers are commenting on portability (which should be identical, assuming C11 with threading support; the thread feature is all or none), but the gist of it (`thread_local` is more convenient/reliable/lightweight, TSS is slightly more flexible since it can be dynamically created at runtime) remains similar. – ShadowRanger Sep 24 '19 at 20:07
  • When you use thread_local then the compiler will take care of the tss_create/get/set calls for you. But they have to provide the backdoor as well, the standard doesn't deal with dynamically loadable modules for example. The odds that you *have* to use the backdoor ought to be low in a compiler that survived the Darwin selection. – Hans Passant Sep 24 '19 at 21:01

1 Answers1

2

Functionally, the important difference is the establishment of a destructor. In your example this is free, but in fact it could be any function with the right signature.

So this gives the possibility for a callback at the end of any thread for doing any kind of cleanup.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177