简体   繁体   中英

Bad practice having 2 locks in same method?

I am wondering if this is a bad code design to have 2 separate locks used in the same method. I believe the reason the two locks were first implemented was the fields they were updating were unrelated.

public class MyClass
{
  private readonly object _lock = new object();
  private readonly object _lock2 = new object();

  public async Task DoStuff()
  {
    lock(_lock)
    {
      //do some stuff
    }
    lock(_lock2)
    {
      //do some other stuff
    }
  }
}

Let's say the _lock is used to only modify an int variable and _lock2 is used to modify and List<string> variable. Both locks can be called from other methods in the class on different threads. Is there a smell for a deadlock here? It seems like I should refactor this so the DoStuff method should only utilize one lock type.

If it's okay for the two blocks of code to be running concurrently from different invocations, then there is no problem with having two objects to lock on. If it's important that the two blocks be able to run at the same time then it's essential that you do have different objects to lock on. If it's important the two blocks not actually run at the same time, and that the entire operation be treated as one logically atomic operation, then you should use one lock .

The two options have entirely different semantics, neither is inherently wrong or inherently right. You need to use the right one for the situation that you're in.

That code is dead lock safe. There is no situation in this code when lock would prevent thread that is already in critical section from leaving it. Therefore this thread will always release obtained lock for another thread

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM