I very much like the idea of the transitive shared attribute in D, but in practice it turns out to be a real pain in the ass. Just try once to write a class A that will work fine both as just 'A' and as 'shared(A)'. If you're very lucky you just have to duplicate all your code in 'shared' methods.
Now think of class A as a container type. Need it be different for A and shared(A)? Apart from synchronisation, no.
Even Phobos' container types Just Don't Work when marked as shared. But shared data is usually meant to be used somehow, doesn't it? So here is my proposal for a solution to most of the trouble:
If a non-static member function is called and the following is all true:
- 'this' is shared
- there is no matching 'shared' overload for the function being called
then do the following:
- search for a matching overload that is not marked as shared
- if found, check it semantically as if it were marked as shared
- if it passes the check, use it, but call it through a synchronisation wrapper
Here, calling through a synchronisation wrapper works like this:
// Assuming:
shared(A) a = cast(shared) new A();
// The following …
a.foo()
// … will expand to:
synchronized(a) { a.foo() }
Feel free to comment!
Comment #1 by Marco.Leise — 2014-10-20T10:09:52Z
That only works well when you don't use your own synchronization. Otherwise you may protect stuff in one shared method with your own mutex, and one some other method you forgot to mark shared, the object's hidden monitor mutex is used, allowing for two threads to modify the data in parallel.
Just imagine what would happen in this code:
auto cond = cast(shared) new Condition(new Mutex);
synchronized (cond.mutex)
{
...
}
... And you just created a new Mutex to protect the Mutex that protects your critical section.
Comment #2 by dlang-bugzilla — 2017-07-21T06:59:58Z
I believe that today enhancement requests to the language itself need to be presented as a D Improvement Proposal:
https://github.com/dlang/DIPs
If you think this proposal still has merit today, please file a DIP. The current DIP manager can assist you through the process.
Closing (also because this issue is over 6 years old and there has been no reply to Marco's comment above.)