title: Difference of Two Cells in An Array of Shared Memory (Concurrency)
body: <p>I have an array in shared memory in a concurrent program, where each thread is directly associated with one cell in the array.  I have a function that is supposed to get the difference between the cell that the thread is associated with with and one of the neighboring cells that that thread isn't associated it.  I'm not sure how to organize the <code>mutex</code>s to protect the memory when a thread is accessing a its own cell or its neighboring cell in the most efficient way.  This is what I currently have, but I'm not sure if there's a better way or not.</p>
  
  <pre><code>// Assume `myArray` is a global int array used for sharing resources between the threads.  
  // Assume `semaphoreArray` is an array of pthread `mutex`s with same size as `my_array`.
  
  int difference (int id, int neighbor) // id allows us to identify the thread
  {
      int currentIdsValue;
      int neighboringIdsValue;
  
      pthread_mutex_lock (&amp; (semaphoreArray[id]));
      currentIdsValue = myArray[id];
      pthread_mutex_unlock (&amp; (semaphoreArray[id]));
  
      pthread_mutex_lock (&amp; (semaphoreArray[neighbor]));
      neighboringIdsValue = myArray[neighbor];
      pthread_mutex_unlock (&amp; (semaphoreArray[neighbor]));
  
      return (currentIdsValue - neighboringIdsValue);
  }
  </code></pre>
  
  <p>I'm wondering if I should be using two semaphore arrays for each cell being accessed in the array.</p>
  
  <p><strong>Note</strong>: The <code>pthread</code> library is required, can't use <code>std::thread</code>, unfortunately.</p>