Sunday, 15 September 2013

c# - Does this nested locking cause deadlock? -



c# - Does this nested locking cause deadlock? -

method1 , method2 public methods. both methods required take in 2 locks in same order. sure acquiring locks in same order not end in deadlock. locks in common() unnecessary?

public void method1() { lock(lockobja) lock(lockobjb) { //dosomething common(); } } public void method2() { lock(lockobja) lock(lockobjb) { //dosomething else common(); } } private void common() { lock(lockobja) lock(lockobjb) { //dosomething else } }

i couldn't find improve reference on rush can remember operating scheme course of study resource locking professor stated acquiring resources in same order doesn't raise chances deadlocks happen.

always acquiring resources in same order

edit: found a stackoverflow question this still no article specific deadlock prevention mechanism...

since c# locks reentrant should not more harm when using code.

back qeustion

if methods private have little scope within class check lock conditions. on public api improve decorate methods changing mutable state locks. if means might reenter on same lock twice. in private api can decide wether appropriate.

edit: after qestion edit

if 3 methods have 1 have in scope, or 3 methods critical ones (modifying/accessing mutable state). , since can see nil more happen can break locking.

then reply yes! in method common locking not neccessary.

note: decorating methods

by decoration mean decoration in sense of decorator pattern. means execute code before , after piece of code. in case mean code within method. in java there exist synchronized key word allows utilize short hand decorate code within method conveniently synchronized block using enclosing instance object. this called synchronized method.

c# .net multithreading locking

No comments:

Post a Comment