How to use globals correctly?

Steven Schveighoffer schveiguy at yahoo.com
Mon Mar 5 18:57:01 UTC 2018


On 3/5/18 1:35 PM, Robert M. Münch wrote:

> If I use VisualD and add a watch on myObj, I don't see anything just a 
> "identifier myObj is undefined". Not sure if this is because of some 
> threads running (using the D RX framework).

Can't answer your visual D questions...

> 
> So, some questions:
> 
> 1. Are myMemb1..N TLS or __gshared as well?

No, they are on the heap. Only the reference is __gshared. But 
effectively it is __gshared, since you can reach those items via the 
global `myObj`.

> 2. How to best implement a simple global to keep track of values (with 
> support for threads)?

shared is the best mechanism, and you don't have to make it a class, it 
can be a struct.

This is only if you are using it as POD (plain old data). If you want to 
have methods, shared kind of sucks.

But this at least tells the type system that it's shared between 
threads. __gshared does not, it just sticks it in global space, but 
pretends it's not shared data.

-Steve


More information about the Digitalmars-d-learn mailing list