title: Locking just one element of a list. Is this the right way?
body: <p>I have a number of threads; some of them share an object; others share another one, while these objects are in a list (Dictionary) shared by all of the threads.</p>
  
  <p>In other words, there is a list of objects, which is shared by all of the threads, though each one of them is using just one object of this list.</p>
  
  <p>I'm not having problems with concurrency by locking the main list in this way:</p>
  
  <pre><code>public class MainClass
  {
      private static List_of_objects list_of_objects;
  
      private static object var = new object();
  
      private static bool list_is_being_used = false;
  
      public void Main()
      {
          lock (var)
          {
              while(list_is_being_used)
              {
                  Monitor.Wait(var);
              }
  
              list_is_being_used = true;
  
              // ... Do some things with an object of the list ...
  
              list_is_being_used = false;
  
              Monitor.Pulse(var);
          }
      }
  }
  </code></pre>
  
  <p>Since each thread is going to use just one element of the list, I would like to lock that element alone, so just the threads using that element get locked while the rest of the threads using other elements don't.</p>
  
  <p>I've thought something like this could do it:</p>
  
  <pre><code>public class MainClass
  {
      private static List_of_objects list_of_objects;
  
      private static object var_x[] = new object [CONSTANT];  // I declare a mutex-variable for each element on the shared list
      ...
  
      private static bool element_x_is_being_used[] = [false,false,false,...];
  
      private ElementClass element; // I declare an object as a pointer to the element this thread is going to use. &lt;---
  
      public void Main()
      {
          element = list_of_objects[1];
  
          ...
  
          lock (object var_x[1]) // I just want to lock this element of the list, not the whole list
          {
              while(element_1_is_being_used)
              {
                  Monitor.Wait(object var_x[1]);
              }
  
              element_1_is_being_used = true;
  
              // ... Do some things with element 1 of the list ...
  
              element.set_whatever... // I change some values of the element
  
              element_1_is_being_used = false;
  
              Monitor.Pulse(object var_x[1]);
          }
      }
  }
  </code></pre>
  
  <p>My question is, can I do it in this way?</p>
  
  <p>I mean, Can I declare a non-static variable as a pointer to an element of a static list of elements assuming all of the process sharing a specific element will access it correctly?</p>