问题
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,
回答1:
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:
- You increase the burden on users of your function/class, increasing design viscosity.
- You make it possible for callers to update shared state without taking the lock.
- You introduce the possibility of deadlocks if different functions take multiple locks in different order.
回答2:
If you use locks internally, you have to note it on manual documentation. Or your code will bottleneck of parallel execution, and users will be hard to know the truth.
回答3:
We are learning that external locking offers advantages if you need to do several interrelated granular operations at once, or work with a reference to an internal structure - you can hold a lock as long as you need your set of work to be safe from other threads.
An example: A container that manages a list of items might want to provide an api to get a mutable reference to one item. Without external locking, as soon as the function call finishes, another thread could potentially lock and mutate data. A plausible solution is to return a copy of the one item, but this is inefficient.
That being said, for some cases, internal locking can have a cleaner api, provided you can be sure that you won't want to preserve a lock longer than one function call.
来源:https://stackoverflow.com/questions/3687740/coding-style-lock-unlock-internal-or-external