Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using __thread in c99

I would like to define a few variables as thread-specific using the __thread storage class. But three questions make me hesitate:

  1. Is it really standard in c99? Or more to the point, how good is the compiler support?
  2. Will the variables be initialised in every thread?
  3. Do non-multi threaded programs treat them as plain-old-globals?
like image 808
Adrian Ratnapala Avatar asked Jul 29 '11 06:07

Adrian Ratnapala


2 Answers

To answer your specific questions:

  1. No, it is not part of C99. You will not find it mentioned anywhere in the n1256.pdf (C99+TC1/2/3) or the original C99 standard.
  2. Yes, __thread variables start out with their initialized value in every new thread.
  3. From a standpoint of program behavior, thread-local storage class variables behave pretty much the same as plain globals in non-multi-threaded programs. However, they do incur a bit more runtime cost (memory and startup time), and there can be issues with limits on the size and number of thread-local variables. All this is rather complicated and varies depending on whether your program is static- or dynamic-linked and whether the variables reside in the main program or a shared library...

Outside of implementing C/POSIX (e.g. errno, etc.), thread-local storage class is actually not very useful, in my opinion. It's pretty much a crutch for avoiding cleanly passing around the necessary state in the form of a context pointer or similar. You might think it could be useful for getting around broken interfaces like qsort that don't take a context pointer, but unfortunately there is no guarantee that qsort will call the comparison function in the same thread that called qsort. It might break the job down and run it in multiple threads. Same goes for most other interfaces where this sort of workaround would be possible.

like image 62
R.. GitHub STOP HELPING ICE Avatar answered Sep 22 '22 04:09

R.. GitHub STOP HELPING ICE


You probably want to read this:

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

1) MSVC doesn't support C99. GCC does and other compilers attempt GCC compatibility.

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

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

2) Only C++ supports an initializer and it must be constant.

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

like image 27
Steve-o Avatar answered Sep 19 '22 04:09

Steve-o