How to use globals correctly?

Steven Schveighoffer schveiguy at yahoo.com
Mon Mar 5 19:46:42 UTC 2018


On 3/5/18 2:39 PM, Robert M. Münch wrote:
> On 2018-03-05 18:57:01 +0000, Steven Schveighoffer said:
> 
>> On 3/5/18 1:35 PM, Robert M. Münch wrote:
>>
>>> 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`.
> 
> Ok, that was my idea. And am I right, that I don't need any special 
> syntax, just: myObj.myMemb

Yes. Like I said, __gshared means it's global, but it's not typed as 
shared. So the compiler will let you do anything you want.


>> If you want to have methods, shared kind of sucks. But this at least 
>> tells the type system that it's shared between threads.
> 
> Why does it suck?

Because you can't call shared methods on a non-shared object, and vice 
versa. Once you start putting more complex data types inside a 
class/struct that is shared, you start not being able to use them. If 
you're just storing strings and integers, it's probably ok.

>> __gshared does not, it just sticks it in global space, but pretends 
>> it's not shared data.
> 
> Ok, so this is the really hackish solution...
> 

__gshared is for those who "know what they are doing". There is more 
exposure to race conditions, and there is a LOT of code that assumes if 
something isn't typed as shared, it's not shared. __gshared is kind of a 
lie in that case, and you can potentially run into problems.

If you're doing simple things, it can possibly be OK, especially if it's 
just for debugging.

-Steve


More information about the Digitalmars-d-learn mailing list