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

Ali Çehreli acehreli at yahoo.com
Sat Apr 1 15:02:12 UTC 2023


On 3/26/23 13:41, ryuukk_ wrote:

 > C, C++, Rust, Zig, Go doesn't do TLS by default for example

C doesn't do because there was no such concept when it was conceived.

C++ doesn't do because they built on top of C.

(D does because it has always been innovative.)

Go doesn't do because it had no innovations anyway.

Does anyone have documentation on why Rust and Zip does not do thread 
local by default? I wonder what experience it was based on.

Speaking of experience, I used to be a C++ programmer. We made use of 
thread-local storage precisely zero times. I think it's because the 
luminaries of the time did not even talk about it.

With D, I take good advantage of thread-local storage. Interestingly, I 
do that *only* for fast code.

void foo(int arg) {
     static int[] workArea;

     if (workArea.length < nededFor(arg)) {
         // increase length
     }

     // Use workArea
}

Now I can use any number of threads using foo and they will have their 
independent work areas. Work area grows in amortized fashion for each 
thread.

I find the code above to be clean and beautiful. It is very fast because 
there are no synchronization primitives needed because no work area is 
shared between threads.

Finding one example to the contrary does not make TLS a bad idea. 
Engineering is full of compromises. I agree with D's TLS by-default idea.


Since I am here, I want to touch on something that may give the wrong 
idea to newer D programmers: D does not have globals. Every symbol 
belongs to a module.

And copying an earlier comment of yours:

 > It's common knowledge that accessing tls global is slow
 > http://david-grs.github.io/tls_performance_overhead_cost_linux/

"TLS global is slow" would be misleading because even the article you 
linked explains right at the top, in the TL;DR are that "TLS may be slow".

Ali



More information about the Digitalmars-d-learn mailing list