Proposal to make "shared" (more) useful
Arafel
er.krali at gmail.com
Thu Sep 13 13:53:49 UTC 2018
Hi all,
I know that many (most?) D users don't like using classes or old,
manually controlled, concurrency using "shared" & co., but still, since
they *are* in the language, I think they should at least be usable.
After having had my share (no pun intended) of problems using shared,
I've finally settled for the following:
* Encapsulate all the shared stuff in classes (personal preference,
easier to pass around).
* When possible, try to use "shared synchronized" classes, because even
if there are potential losses of performance, the simplicity is often
worth it. This mean that the classed is declared:
```
shared synchronized class A { }
```
and now, the important point:
* Make all _private non-reference fields_ of shared, synchronized
classes __gshared.
AIUI the access of those fields is already guaranteed to be safe by the
fact that *all* the methods of the class are already synchronized on
"this", and nothing else can access them.
Of course, assuming you then don't escape references to them, but I
think that would be a *really* silly thing to do, at least in the most
common case... why on earth are they then private in the first place?.
Now, the question is, would it make sense to have the compiler do this
for me in a transparent way? i.e. the compiler would automatically store
private fields of shared *and* synchronized classes in the global storage.
Bonus points if it detects and forbids escaping references to them,
although it could also be enough to warn the user.
This way I think there would an easy and sane way of using shared,
because many of its worst quirks (for one, try using a struct like
SysTime that overrides OpAssign, but not for shared objects, as a field)
would be transparently dealt with.
A.
More information about the Digitalmars-d
mailing list