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

Steven Schveighoffer schveiguy at gmail.com
Mon Mar 27 14:09:45 UTC 2023


On 3/26/23 4:41 PM, ryuukk_ wrote:
> On Sunday, 26 March 2023 at 19:08:32 UTC, Steven Schveighoffer wrote:
>> On 3/26/23 2:07 PM, ryuukk_ wrote:
>>> Hi,
>>>
>>> It's common knowledge that accessing tls global is slow 
>>> http://david-grs.github.io/tls_performance_overhead_cost_linux/
>>>
>>> What i do not understand is the reasoning behind choosing tls global 
>>> by default in D
>>
>> If you know a variable is not `shared`, then you know it can only be 
>> accessed from the current thread. This has huge implications for 
>> thread access.
>>
>> However, one problem that D has no good solution is passing 
>> thread-local data to another thread (to be owned by the new thread, 
>> and no access in the current thread). That's typically the most common 
>> use case for "shared data".
>>
> 
> I haven't explored this use case, that must explain why i find it 
> surprising, however, i read about other languages too, and they seem to 
> be explicit whenever they make use of TLS
> 
> C, C++, Rust, Zig, Go doesn't do TLS by default for example

If you want to have the type system tell you when a variable is readable 
from other threads or not, you need to have *something* to distinguish 
them. 99% of all variables are not readable from other threads, so 
making that the default seems the right call to me.

I don't know if you have thought through the implications. Start with 
the requirement that I need to know by examining the type whether the 
value is viewable from multiple threads. Is there a better mechanism 
with better defaults? C/C++ is precisely the wrong answer -- just let 
the programmer fend for himself. I haven't used the others to know what 
their story is.

One possibility is to REQUIRE you to mark module-level and static 
variables as one of `__gshared`, `shared`, `immutable`, or `@tls`. I 
would be OK with such a change.

I've run into a situation where I want to make a thread local pointer to 
shared data, and it's not easy. The only solution I could come up with 
is to put it inside a dummy struct with a shared member. Having a `@tls` 
storage class would help solve that.

-Steve


More information about the Digitalmars-d-learn mailing list