Andrew Stitcher wrote:
I've just been doing a little thinking and reading about improving the
scalability of the C++ broker: One of the things that occurred to me is
that some things may be improved by using thread local variables to
avoid globally shared state and hence locking. In particular in places
where things are guaranteed to happen on the same thread - for example
the processing of an incoming frame.
Looking into this it appears that gcc has an extension that allows you
to declare thread local variables ("__thread"). Previously I've used the
equivalent Visual Studio magic (something like __declspec(thread)), so I
imagine it's a widespread extension.
Does anyone have experience of using thread local vars with these
extensions? Are there any opinions about using a non-standard feature
like this in a core place in the C++ broker?
Haven't used the gcc extensions but I've used portable TLS templates
(old job, proprietary code) Getting shutdown/delete right is hours of
fun. As long as we wrap the use of __thread in a class we can always
replace it with a native TLS impl if/when we need to support another
compiler so I don't see anything disastrous in using gcc extensions.
E.g. boosts atomic_count takes this tack - using gcc extensions if built
with gcc and using platform atomics or fall-back to mutex.
TLS is bad for the same reasons global variables are bad and then some.
In general I would much prefer to keep thread context on the thread's
stack. TLS does have its uses but in my experience they're mostly about
working around an existing broken design that can't be changed for some
reason. I would consider it only if I'm convinced that it's the only way
to solve some problem, but I would look hard for alternatives first.
Major caveat: TLS is a very rare resource on some platforms - as few 512
variables on some platforms. So it's very important to use a small
fixed number of slots, preferably 1. Under *no circumstances* should
non-singleton objects have TLS members.
Cheers,
Alan.