views:

39

answers:

2

Hello,

Another possibly inane style question:

How should concurrency be locked? Should the executor or caller be responsible for locking the thread?

e.g. in no particular language...

Caller::callAnotherThread() {
    _executor.method();
}

Executor::method() {
    _lock();
    doSomething();
    _unlock();
}

OR

Caller::callAnotherThread() {
    _executor.lock()
    _executor.method();
    _executor.unlock()
}

Executor::method() {
    doSomething();
}

I know little about threading and locking, so I want to make sure the code is robust. The second method allows thread unsafe calls... you could technically call _executor.method() without performing any kind of lock.

Help?

Thanks,

A: 

It depends, but you could always synchronize access to a method outside the class if locks are needed. It is a question of choice.

Of course it's a simplification of the matter. Quite possibly method shares state with other methods of the object so you'll need to make sure all access to the object is synchronized. At least when you can't be sure. If you synchronize method but not method2; which mutates the same stuff as method you could say your syncronization was in vain.

The object (should) have more intimate knowledge about it's workings and could thus do a better job.

Skurmedel
+2  A: 

The callee, not the caller should do the locking. The callee is the only one who knows what needs to be synchronized and the only one who can ensure that it is. If you leave locking up to the callers, you do three bad things:

  1. You increase the burden on users of your function/class, increasing design viscosity.
  2. You make it possible for callers to update shared state without taking the lock.
  3. You introduce the possibility of deadlocks if different functions take multiple locks in different order.
Peter Ruderman
+1. Good points, but I think there are valid situations where you could lock outside as well.
Skurmedel
Good, that's how I have it so far. :D
Stephen Furlani