synchronization code smell? -
i analyzing lot of multi-threaded code , i'm seeing many locks. methods have 2 locks in row this:
classa::foo() { locka.lock(); lockb.lock(); ...//do stuff lockb.unlock(); locka.unlock(); }
my question general (and can't provide actual code). code smell? bad practice? can't prove code can simplified, seems if coded correctly there wouldn't need locking 2 things. lock should manage set of resources need synchronization, right? if there 2 locks overlap management of resources, there deadlocking issues?
please let me know if have insight.
thanks, jbu
it might smell, might not, depending on context , project scope. if find juggling 5 locks syncronize queued list, maybe doing wrong. want have nice 1-1 ratio between shared resources , locks.
sometimes can tempting lock on finer-grind levels (ie. use lock on each item of list rather lock entire list). rezist urge until profiler tells lock heavily-contented.
othertimes should able group several locks single 1 using locks not protect single resource, protect part of bussiness-logic know shouldn't have lot of contention. may lose little bit of performance, if can rid of 10 locks it's worth simplicity brings table.
i guess answer question in form of question: why classa using 2 shared resources @ same time? that's try avoid in design phase using sort of single-responsibility-principle. shared resource belongs , single authority regard locking/unlocking resource.
is there way can refactor method to:
locka.lock(); //some code locka.unlock(); lockb.lock(); //some other code lockb.unlock();
one definite thing make sure: there should predetermined finite/defined way of ordering locks (ie locka > lockb) , lock them in ascending order.
you should never case of
locka.lock(); lockb.lock();
and in other code
lockb.lock(); locka.lock();
Comments
Post a Comment