1

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?

Properly locking a List<T> in MultiThreaded Scenarios?

Community
  • 1
  • 1
  • If using ,net 4, you migh consider [Thread-Safe Collections](http://msdn.microsoft.com/en-us/library/dd997305.aspx) – 001 Jan 30 '13 at 20:58
  • 1
    I think you meant to add an item to `_list2` in `Method2`. Otherwise they're just two methods doing the same thing. – Adi Lester Jan 30 '13 at 20:58
  • @AdiLester c&p error, i corrected it –  Jan 30 '13 at 21:03

2 Answers2

1

Should i use 2 lock variables or is 1 enough, does it hit performance?

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.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • What do you mean with "can decrease"? If i use 3 Methods on 3 Lists would it be up to 3 times faster with 3 lock variable or would it be maybe 1 1/100 times faster? No Method will use both Lists. –  Jan 30 '13 at 21:02
  • @RobertP. The methods would have to wait on each other, which means that a long running method will block the shorter ones the entire time it's running - basically, you'll only get one thread using any list at any time. It may be a bottleneck, it may not - depends on how things are used. – Reed Copsey Jan 30 '13 at 22:48
0

Lock is very fast (few nanoseconds if I remember it right). 3-4 locks is not a real question.

or in other words - if 4 locks will be too slow for your app - you need to change the approach altogether and look for lock-free algorithms instead which is non-trivial.

I'd say a hundred of locks seems suspicious but 3-4 I wont even waste time to ask about it.

Boppity Bop
  • 9,613
  • 13
  • 72
  • 151