Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to lock code areas

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));
  }
.....
like image 646
0x49D1 Avatar asked Oct 09 '22 03:10

0x49D1


1 Answers

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

like image 123
Oleg Dok Avatar answered Oct 13 '22 10:10

Oleg Dok