Why is it necessary to use synchronized functions when passing shared variables?

Jonathan M Davis jmdavisProg at gmx.com
Sat Mar 5 21:14:46 PST 2011


On Saturday 05 March 2011 20:00:07 d coder wrote:
> 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;
>   }
> }

It's probably complaining because using shared without synchronizing is 
generally very foolish. Now, I would have _thought_ that it would still work 
without, but I apparently not. Regardless, I'm not sure why you'd want to use 
shared anything without synchronizing your access of it. Not synchronizing your 
access of shared variables is pretty much guaranteeing a race condition unless 
you're only accessing them from a single thread, in which case, there's no 
reason for them to be shared in the first place.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list