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?
To answer your specific questions:
__threadvariables start out with their initialized value in every new thread.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 likeqsortthat don’t take a context pointer, but unfortunately there is no guarantee thatqsortwill call the comparison function in the same thread that calledqsort. 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.