0

Suppose I have the two following methods:

Object sync = new Object();
…
public void method1() { lock(sync) { … } }
public void method2() { lock(sync) { method1() … }}

My question here is would this cause any deadlock? Looks like method2 is trying to obtain lock sync when it is already holding it.

Yinfang Zhuang
  • 443
  • 1
  • 5
  • 15

2 Answers2

2

No, it won't cause any deadlocks. lock statement is converted into System.Threading.Monitor Enter and Exit calls. Documentation says:

It is legal for the same thread to invoke Enter more than once without it blocking; however, an equal number of Exit calls must be invoked before other threads waiting on the object will unblock.

You call lock both times from the same thread, so deadlock won't occur.

ingvar
  • 4,169
  • 4
  • 16
  • 29
  • That being said, it is generally a bad Idea to share a mutex object, unless those opeartions are truly mutualyl exclusive (like a add and remove operation on a ConcurrentList). You use a dedicated, private object **because** there is no way some other code could even try to lock it in the first place. – Christopher Oct 14 '18 at 21:38
1

This would not cause a deadlock as the call from method2 to method1 would be on the same thread. Lock only syncronises calls across threads, not on the same thread. See the MS docs for more info.

Code Ranger
  • 401
  • 3
  • 7