Why are globals set to tls by default? and why is fast code ugly by default?

IGotD- nise at nise.com
Sat Apr 1 08:47:54 UTC 2023


On Sunday, 26 March 2023 at 18:25:54 UTC, Richard (Rikki) Andrew 
Cattermole wrote:
> Having TLS by default is actually quite desirable if you like 
> your code to be safe without having to do anything extra.
>
> As soon as you go into global to the process memory, you are 
> responsible for synchronization. Ensuring that the state is 
> what you want it to be.
>
> Keep in mind that threads didn't exist when C was created. They 
> could not change their approach without breaking everyone's 
> code. So what they do is totally irrelevant unless its 1980.
>
> I think its the correct way around. You can't accidentally 
> cause memory safety issues. You must explicitly opt-into the 
> ability to mess up your programs state.

I think "safe" BS is going too far. Normally you don't use global 
variables at all but if you do the most usual is to use normal 
global variables with perhaps some kind of synchronization 
primitive. TLS is quite unusual and having TLS by default might 
even introduce bugs as the programmer believes that the value can 
be set by all threads while they are independent.

Regardless, __gshared in front of the variable isn't a huge deal 
but it shows that the memory model in D is a leaking bucket. Some 
compilers enforce synchronization primitives for global variables 
and are "safe" that way. However, sometimes you don't need them 
like in small systems that only has one thread and it just gets 
in the way.

TLS by default is mistake in my opinion and it doesn't really 
help. TLS should be discouraged as much as possible as it is 
complicated and slows down thread creation.


More information about the Digitalmars-d-learn mailing list