Shared method problem
tcak
tcak at pcak.com
Wed Feb 12 01:30:23 PST 2014
Whenever I start writing a class which would support "shared"
methods, either there are lots of duplicate methods come into
class, synchronisation code required.
PROBLEM 1: Duplication
Look at the code below:
class NamedPipe{
private string filename;
private int mode;
public this(string filename, int mode){
// cast is used to fix `shared` problem
this.filename = cast( typeof(this.filename) )filename;
this.mode = cast( typeof(this.mode) )mode;
}
}
If I define the constructor WITHOUT "shared" keyword, and try to
create a shared object as `auto pipe = new shared
NamedPipe("/tmp/pipe", 432);`, compiler tells me, I can't do this
with shared keyword. If I define the constructor WITH "shared"
keyword, and try to create a non-shared object, again compiler
gives error. So, it is pushing me to either duplicate constructor
or do casting. Some of you may say `pure` function etc., though
if you are writing a complex class, that may not be possible. So,
duplication is inevitable.
PROBLEM 2: Synchronisation
Let's say I want to write a method that will do synchronisation
ONLY IF the method is called from a shared object.
public void updateMode( int newMode ){
// THIS IS NOT SHARED. CHANGE IT IMMEDIATELY.
mode = newMode;
}
public void updateMode( int newMode ) shared{
// THIS IS SHARED. SYNCHRONISE WHILE CHANGING.
synchronized( this ){
mode = newMode;
}
}
The above code is good, but same method is duplicated again just
to be able to enable synchronisation on shared method. So,
non-shared method can run at much higher speed if it is to be
called so many times.
CONCLUSION:
In the current implementation, duplication is almost inevitable,
and if codes are long, then God help us. Long maintenance and
error prone coding.
To be able to solve this, I thought a coding style as below:
public void foo(){
static if( is(this: shared) ){
// some of codes come here if the object is shared
}
else{
// some of codes come here if the object is not shared
}
}
But unfortunately it doesn't work in this way.
Is there really need to allow shared objects different methods,
and non-shared objects different methods? Why don't we separate
implementation instead of methods according to being shared?
More information about the Digitalmars-d
mailing list