March 06, 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
March 06, 2011
>
>
> 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.



Thanks Jonathan

Actually in my actual use case, I am using synchronized at code block level -- to limit the scope of locking. I am doing this to mitigate possible inefficiency due to indiscriminate use of mutex locked code.

But D is forcing me to synchronize at function level, thus making most of my code go under mutex locks.

Regards
- Puneet