www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Why is it necessary to use synchronized functions when passing shared

--002215048eaf8dd971049dc86c54
Content-Type: text/plain; charset=ISO-8859-1

Greetings

Why is it necessary to use synchronized functions when passing shared
variables? I get error even when I am not modifying the shared variable in
the function.
Kindly look at the following code. I get a compile error unless I declare
the functions parent and root synchronized.

The compile error says:
test.d(13): Error: function test.HierObject.root () const is not callable
using argument types () shared const

Thanks and Regards
- Puneet

// Reduced Code
import std.exception;

// synchronized // Compiles without error when uncommented
class HierObject {
  private shared HierObject _root;
  private shared HierObject _parent;

  shared(const(HierObject)) root() const {
    if(_root) return _root;
    else {
      enforce(_parent,
      "HierObject Instance does not have a parent!");
      return this.parent().root();
    }
  }

  shared(const(HierObject)) parent() const {
    enforce(_parent);
    return _parent;
  }
}

--002215048eaf8dd971049dc86c54
Content-Type: text/html; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable

Greetings<div><br></div><div>Why is it necessary to use synchronized functi=
ons when passing shared variables? I get error even when I am not modifying=
 the shared variable in the function.</div><div>Kindly look at the followin=
g code. I get a compile error unless I declare the functions parent and roo=
t synchronized.</div>

<div><br></div><div>The compile error says:</div><div>test.d(13): Error: fu=
nction test.HierObject.root () const is not callable using argument types (=
) shared const</div><div><br></div><div>Thanks and Regards</div><div>- Pune=
et</div>

<div><br></div><div>// Reduced Code</div><div><div><div>import std.exceptio=
n;</div><div><br></div><div>// synchronized // Compiles without error when =
uncommented</div><div>class HierObject {</div><div>=A0 private shared HierO=
bject _root;</div>

<div>=A0 private shared HierObject _parent;</div><div><br></div><div>=A0 sh=
ared(const(HierObject)) root() const {</div><div>=A0 =A0 if(_root) return _=
root;</div><div>=A0 =A0 else {</div><div>=A0 =A0 =A0 enforce(_parent,</div>=
<div><span class=3D"Apple-tab-span" style=3D"white-space:pre">	</span> =A0 =
=A0 =A0&quot;HierObject Instance does not have a parent!&quot;);</div>

<div>=A0 =A0 =A0 return this.parent().root();</div><div>=A0 =A0 }</div><div=
=A0 }</div><div><br></div><div>=A0 shared(const(HierObject)) parent() cons=

div><div>=A0 }</div> <div>}</div></div></div><div><br></div> --002215048eaf8dd971049dc86c54--
Mar 05 2011