Shared object must have synchronized interface?

Jonathan M Davis jmdavisProg at gmx.com
Sat May 11 20:44:01 PDT 2013


On Sunday, May 12, 2013 04:54:25 Domain wrote:
> class A
> {
>      public synchronized void test1()
>      {
>      }
> 
>      public void test2()
>      {
>      }
> }
> 
> int main(string[] argv)
> {
>      auto a1 = new shared(A)();
>      a1.test1();
>      a1.test2();
> 
>      auto a2 = new A();
>      a2.test1();
>      a2.test2();
> }
> 
> Error: function main.A.test2 () is not callable using argument
> types () shared
> Error: function main.A.test1 () shared is not callable using
> argument types ()
> 
> So, if I want a class support both shared and non-shared, I must
> override all method?

Overload technically, but yes (override means implementing the same function 
that was in a base class with the same signature (save perhaps for a covariant 
return type), whereas overload means providing a function with the same name 
but a different signature).

I believe that the way that shared objects are typically handled at this point 
is that if you want to call functions on them, you protect them within a 
synchronized block or with a mutex, and then you cast them to non-shared while 
you use it (and treat it as shared again once you've exited the synchronized 
block or unlocked the mutex). Actually trying to call functions on a shared 
object is a royal pain precisely because you have to overload everything. But 
as long as access to the object is appropriately protected, it's perfectly 
safe to cast the object to non-shared in order to use it. You just have to 
make sure that access to the object is indeed protected so that only one 
thread is accessing it while it's being operated on as non-shared (or you'll 
get really nasty bugs).

A class with synchronized functions can be used to protect a shared object, 
but the functions being called on the shared object would still have to be 
shared (or the shared object would have to be non-shared) in order to call 
them.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list