Synchronisation help

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Jan 2 16:39:18 UTC 2024


On Tuesday, January 2, 2024 4:39:12 AM MST Anonymouse via Digitalmars-d-learn 
wrote:
> On Tuesday, 2 January 2024 at 11:05:33 UTC, user1234 wrote:
> > Do not use `shared` AA. Use `__gshared` + sync primitives.
> > `shared` AA will lead to all sort of bugs:
> >
> > - https://issues.dlang.org/show_bug.cgi?id=20484#c1
> > - https://issues.dlang.org/show_bug.cgi?id=17088
> > - https://issues.dlang.org/show_bug.cgi?id=16597
> > - etc.
>
> Hmm, I see.
>
> Is `shared` safe to use with AAs *provided* I use sync
> primitives, or should I favour `__gshared` over `shared`? I was
> under the impression `__gshared` was only really meant for
> interfacing with C.

You should almost never use __gshared. It's really only intended to be used
with C global variables.

Some folks use __gshared, because they don't like the restrictions that
shared places on your code, but the restrictions are there to protect you
from accessing shared data when it's not properly protected. In general,
what code should be doing is marking variables as shared so that you cannot
accidentally access the data, and then in the sections of code where you've
properly protected access to the data, you temporarily cast away shared to
operate on it. This is obviously a tad annoying, which is why some folks
then just use __gshared to shut up the compiler, but it's very much on
purpose that things work this way, and if you mark a variable as __gshared,
the type system treats it as thread-local, and it's never caught when you
try to access the variable without first dealing with the proper
synchronization primitives.

Unless a type is specifically designed to work as shared (e.g. a class or
struct with shared member functions which do all of the appropriate locking
and casting internally), it's expected that you're going to have to either
cast away shared or use atomics to operate on shared variables of that type.
And AAs are designed to be thread-local, so they have no locking mechanisms
built in, and you have to deal with the locking primitives yourself as well
as casting away shared to then operate on the AA while it's protected. It's
a bug when you can do pretty much anything with a shared AA other than pass
it around without casting away shared first.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list