Encoding style: lock / unlock internal or external?

Another perhaps style question:

How should concurrency be blocked? Should the agent or caller be responsible for blocking the flow?

eg. in any 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 streaming and blocking, so I want to make sure the code is reliable. The second method allows you to use unsafe thread calls ... you can technically call _executor.method () without any locks.

reference

Thanks,

+1
source share
2 answers

The call, not the caller, must do the lock. The caller is the only one who knows what needs to be synchronized, and the only one who can verify this. If you leave the lock to subscribers, you will do three bad things:

  • You increase the load on users of your function / class by increasing design viscosity.
  • You allow subscribers to update the shared state without blocking.
  • You enter the possibility of deadlocks if different functions perform multiple locks in a different order.
+3
source

If you use internal locks, you should note this in the manual documentation. Or your code will be the bottleneck of parallel execution, and it will be difficult for users to find out the truth.

0
source

All Articles