How to prevent a deadlock when you need to block multiple objects

Image of this code:

You have 2 arrays and you need to lock both of them at the same moment (for some reason - you just need to lock both of them because they are somehow dependent on each other) - you can insert a lock

lock (array1) { lock (array2) { ... do your code } } 

but this can lead to a deadlock if someone from another part of your code executes

 lock (array2) { lock (array1) { ... do your code } } 

and array 1 was blocked - the execution context switched - then array 2 was blocked by the second thread.

Is there any way to atomize them? such as

 lock_array(array1, array2) { .... } 

I know that I can just create an additional โ€œlock objectโ€ and lock it, and not for all arrays in my code, but this seems to me wrong ...

+4
source share
3 answers

In general, you should avoid blocking on public elements (arrays in your case). You would prefer to have a private static object that you would block.

+5
source

You should not prohibit locking a public variable, as Darin said. for instance

 public class Foo { public object Locker = new object(); } public class Bar { public void DoStuff() { var foo = new Foo(); lock(foo.Locker) { // doing something here } } } 

rather do something like this.

 public class Foo { private List<int> toBeProtected = new List<int>(); private object locker = new object(); public void Add(int value) { lock(locker) { toBeProtected.Add(value); } } } 

The reason for this is that you have multiple threads accessing multiple public synchronization constructs, and then launch a very real dead end possibility. Then you have to be very careful about how you code. If you make your library accessible to others, can you be sure you can capture the castle? Perhaps someone using your library has also taken over the castle, and between you you have come to a standstill. For this reason, Microsoft recommends not using SyncRoot.

+4
source

I'm not sure what you mean by array locking. You can easily perform an operation on both arrays in a single lock.

 static readonly object a = new object(); lock(a){ //Perform operation on both arrays } 
+1
source

Source: https://habr.com/ru/post/1481890/


All Articles