How to use globals correctly?

Marc jckj33 at gmail.com
Mon Mar 5 19:25:56 UTC 2018


On Monday, 5 March 2018 at 18:57:01 UTC, Steven Schveighoffer 
wrote:
> 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

Can __gshared be used instead of static in the singleton pattern? 
I, comming from C++, ignorantly, have never used _gshared so I 
went to static instead of (being static also means thread-safe, 
as far I know)...


More information about the Digitalmars-d-learn mailing list