On Monday, 1 June 2020 at 12:37:05 UTC, Steven Schveighoffer
wrote:
I was under the impression that TLS works by altering a global
pointer during the context switch. I didn't think accessing a
variable involved a system call.
For sure they are slower than "normal" variables, but how much
slower? I'm not sure.
It depends, there several different optimizations possible. This
is essentially the difference between the -fPIC and -fpie flag
GNU compilers. -fpie can optimize TLS so that it is an offset
from a certain register (fs or gs with x86). Otherwise the
compiler insert __tls_get_addr. Typically shared objects gets
this call, but the executable can optimize. So if druntime is a
shared object, it will use __tls_get_addr. TLS variables will not
be major hit if used moderately, used in a loop, then you will
certainly see a performance hit.
This can only take you so far, when the language uses TLS by
default. The GC has to support scanning TLS and so it uses TLS
to track thread-specific data.
Yes, this was some of the annoyance I had when porting druntime.
The thread startup code needed to use link library (like
elf/link.h for linux) in order to obtain the entire TLS area
(areas because there a several of them). This includes scanning
sections during startup and it becomes even more complicated with
runtime loaded modules. Basically there is a lot of boiler plate
in druntime just for reading the executable format. druntime has
tons of elf stuff in it just to load a program something I'm not
too keen on, because it's a lot of code and you need to support
all the quirks with different CPU archs and operating systems.
You'd want druntime to be more OS agnostic a let the OS services
deal with the TLS stuff. The only upside can be that you can have
a full symbolic stack trace during aborts when a poking in the
executable formats.
Well, that's how it is because of GC and there is not really any
way around it. A non tracing GC would not have this requirement
though. When you dig into these details you realize how heavy the
D language really is and some solutions get negative beauty
points.