Reputation: 8704
What is better:
to have large code area in lock statement
or
to have small locks in large area?..
exchanges in this sample are not changable.
lock (padLock)
{
foreach (string ex in exchanges)
{
sub.Add(x.ID, new Subscription(ch, queue.QueueName, true));
.........
}
or
foreach (string ex in exchanges)
{
lock (padLock)
{
sub.Add(x.ID, new Subscription(ch, queue.QueueName, true));
}
.....
Upvotes: 5
Views: 650
Reputation: 16441
I think there are two different questions:
1. Which would be correct?
2. Which would give better performance?
The correctness question is complicated. It depends on your data structures, and how you intend the lock to protect them. If the "sub" object is not thread-safe, you definitely need the big lock.
The performance question is simpler and less important (but for some reason, I think you're focused on it more).
Many small locks may be slower, because they just do more work. But if you manage to run a large portion of the loop code without lock, you get some concurrency, so it would be better.
Upvotes: 1
Reputation: 1959
You can't effectively judge which is "right" with the given code snippets. The first example says it is not OK for people to see sub with only part of the content from exchanges. The second example says it is OK for people to see sub with only part of the content from exchanges.
Upvotes: 0
Reputation: 62439
In this particular case, the best option is the first one, because otherwise you're just wasting time locking/unlocking since you have to execute the entire loop anyway. So there's not much opportunity for parallelism in a loop that executes individually atomic operations anyway.
For more general advice on critical section sizes check this article: http://software.intel.com/en-us/articles/managing-lock-contention-large-and-small-critical-sections/
Upvotes: 1
Reputation: 21756
The wider lock - the less you get from multithreading, and vice versa So, use of locks completely depends on logic. Lock only things and places which changing and have to run only by one thread in a time
If you lock for using the collection sub
- use smaller lock, but if you run multiple simultaneous foreach
loops in parallel
Upvotes: 1
Reputation: 30097
Good practise would be to only lock that area which you want to be executed by only one thread at a given time
If that area is whole foreach loop then first approach is fine
but if that area is just one line as you have shown I second approach then go for the second approach
Upvotes: 1