Using __thread in c99

I would like to define several variables depending on the thread using the storage class __thread. But three questions make me shy:

  • Is this really the standard in c99? Or what's more, how good is compiler support?
  • Will the variables in each thread be initialized?
  • Do not multiprocessor programs treat them like regular-globals?
+4
source share
2 answers

To answer your specific questions:

  • No, this is not part of the C99. You will not find it anywhere in n1256.pdf (C99 + TC1 / 2/3) or in the original C99 standard.
  • Yes, __thread variables start with their initialized value in each new thread.
  • In terms of program behavior, local storage class variables behave in much the same way as simple global variables in programs that are not associated with multiple threads. However, they will incur a bit more runtime (memory and startup time), and there may be problems with restrictions on the size and number of local thread variables. All this is quite complicated and depends on whether your program is a static or dynamic link and whether the variables are in the main program or in the shared library ...

Outside of the C / POSIX implementation (e.g. errno , etc.), the thread-based class, in my opinion, is actually not very useful. This is pretty much a crutch to avoid a clean transfer around the required state in the form of a context pointer or the like. You might think that this can be useful for overcoming broken interfaces like qsort that do not accept a context pointer, but unfortunately there is no guarantee that qsort will call the comparison function in the same thread called qsort . This can break the job and run it in multiple threads. The same goes for most other interfaces where possible.

+5
source

You probably want to read this:

http://www.akkadia.org/drepper/tls.pdf

1) MSVC does not support C99. GCC also makes other compilers try GCC compatibility.

edit The breakdown of compiler support for __thread is available here:

http://chtekk.longitekk.com/index.php?/archives/2011/02/C8.html

2) Only C ++ supports the initializer and it must be permanent.

3) Non-threaded applications are single-threaded applications.

+2
source

All Articles