On 14/7/20 10:45, Dominikus Dittes Scherkl wrote:
This is generally true. Avoid sharing many variables!
Tasks should be as independent from each other as possible. Anything
else is bad design doomed to run into problems sooner or later.
Also there is really almost never a good reason to share whole classes
or nested structures.
Sometimes you want to encapsulate your "shared" logic.
For instance, a class (or struct) might be a thread-safe container
responsible for storing shared data across multiple threads. Each thread
would get a shared reference to the container, and all the
synchronization would be managed internally by that class.
In these cases I just marked the whole container class as `shared`
instead of having to mark every single method, in fact there were no
non-shared methods at all.
Now I know that the members shouldn't be shared, just the methods, but
the difference wasn't clear to me until now, because it only shows when
you cast shared away from `this`.
If you only instantiate shared variables, all the members become
automatically shared as well, even if they originally weren't. So far I
was just removing shared from the individual members, so I didn't notice:
```
import std;
class S {
SysTime a;
shared SysTime b;
synchronized shared void setIt(SysTime t) {
// What I used to do
cast () a = t; // Here you need to cast away shared anyway
cast () b = t; // so it doesn't make any difference.
// What I'll do from now on
with(cast() this) { // You only notice the difference when you
cast away `shared` from `this`
a = t;
// b = t; // FAILS
}
}
}
```