Should i use 2 lock variables or is 1 enough, does it hit performance? What if i would had 3 or 4 Methods that i call from several threads?
public static class Foolocking
{
private static object _syncRoot = new object();
private static List<string> _list1;
private static List<string> _list2;
public Foolocking()
{
_list1 = new List<string>();
_list2 = new List<string>();
}
public void Method1(string s1)
{
lock (_syncRoot)
{
_list1.Add(s1);
}
}
public void Method2(string s2)
{
lock (_syncRoot)
{
_list2.Add(s2);
}
}
}
Reffering to this, would it be correct to lock list1 and list2 itsself?
If you use two lock variables, each list could be added to from separate threads at the same time.
If you use a single lock variable, then the two threads will wait on each other. This will potentially cause more thread contention, which can decrease overall throughput.
Separate locking variables for each object will potentially help performance at the cost of more complexity. That being said, if you’re using both lists within a single method, and need to lock both of them, two lock variables adds the potential for a deadlock, so extra care would be required.