Difference between __gshared and shared.
Jonathan M Davis via Digitalmars-d
digitalmars-d at puremagic.com
Thu Jul 9 09:03:47 PDT 2015
On Thursday, 9 July 2015 at 14:40:17 UTC, John Colvin wrote:
> Basically, __gshared pretends to compatible with C(++) globals,
> but in actual fact it doesn't share the same memory model so
> who knows what might happen... It's not just
> dangerous-so-be-very-careful, it's fundamentally broken and
> we're currently just getting away with it by relying on C(++)
> optimisers.
__gshared is required for interacting with C/C++ APIs, but
really, even there, what you're mainly dealing with is primitive
types like int, and access to it should normally be pretty
minimal/restricted. That being said, C/C++ bindings in general
are arguably a giant hole, because they're marked as non-shared
when they're arguably shared. It usually works fine, because the
C/C++ functions generally aren't doing anything with what you
pass to them which would cause them to be used across multiple
threads, and you're usually not doing a lot of passing around of
data that you get from C/C++ functions, but it _is_ an area that
is a bit of minefield if you're not careful. You're basically
dealing with the __gshared problem. Unfortunately, I'm not sure
what we can do about it. Simply marking it all as shared would be
problematic, since most of it really isn't, but having it all be
treated as thread-local is also problematic. So, unfortunately,
you just have to be very careful when dealing with C/C++ bindings
and understand what the C/C++ code is doing. It is a problem
though.
Still, using __gshared more than you have to is just going to
make the problem bigger. It's bad enough that we have to deal
with it at the C/C++ binding layer without having to worry about
it in straight up D code.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list