title: C++ Avoid "False sharing" in OpenMP
body: <p>I'm trying to parallelize some iterations over a matrix.</p>
  
  <p>The matrix is saved in a 1D array to have contiguous data in memory:</p>
  
  <pre><code>// array that contains all the elems of dense matrix
  char* data;
  //set of pointers to the matrix rows indexed by the subarrays of 'data'
  char ** dense = NULL;
  dense = new char*[m_rows];
  data = new char[m_cols*m_rows];
  </code></pre>
  
  <p>After 'data' has been populated with numbers, I index the matrix in that way:</p>
  
  <pre><code>// index every row of DENSE with a subarray of DATA
  char* index = data;
  for(int i = 0; i &lt; m_rows; i++)
  {
      dense[i] = index;
      // index now points to the next row
      index += m_cols;
  }
  </code></pre>
  
  <p>After that, I parallelize the iteration over the matrix assigning a column to every thread because I have to make computations column by column.</p>
  
  <pre><code>    int th_id;
      #pragma omp parallel for private(i, th_id) schedule(static)
      for(j=0;j&lt;m_cols;++j)
      {
          for(i=0;i&lt;m_rows;++i)
          {
              if(dense[i][j] == 1)
              {
                  if(i!=m_rows-1)
                  {
                      if(dense[i+1][j] == 0)
                      {
                          dense[i][j] = 0;
                          dense[i+1][j] = 1;
                          i++;
                      }
                  }
                  else
                  {
                      if(dense[0][j] == 0)
                      {
                          dense[i][j] = 0;
                          dense[0][j] = 1;
                      }
                  }
              }
          }
      }
  </code></pre>
  
  <p>I think that I came across the "False sharing" problem in which cache data are invalidated when a matrix cell is written.</p>
  
  <p>How can I solve this problem?</p>