问题
I would like to define a few variables as thread-specific using the __thread storage class. But three questions make me hesitate:
- Is it really standard in c99? Or more to the point, how good is the compiler support?
- Will the variables be initialised in every thread?
- Do non-multi threaded programs treat them as plain-old-globals?
回答1:
To answer your specific questions:
- 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.
- Yes,
__thread
variables start out with their initialized value in every new thread. - 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.
回答2:
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.
来源:https://stackoverflow.com/questions/6869391/using-thread-in-c99