title: Atomic-based lock for thread-safe use of elements
body: <p>I want to create a thread-safe routine that executes in parallel (with OpenMP) and accesses several elements. The elements are basically structs with a couple variables and an array. Threads can access these elements from several points. I have multiple (a variable no. of) arrays with pointers to the elements in my program. So, it is possible that one thread T1 access one element E via one array A1, and another thread T2 accesses the same element via another array A2.</p>
  
  <p>What I thought about doing was to create the following structure:</p>
  
  <pre><code>//try to use element E in array 1     
  
  #pragma omp flush(array1[E]-&gt;lock)
     if(!array1[E]-&gt;lock){
        array1[E]-&gt;lock = 1;
  
        ...//use (either read, write or both) element
  
        array1[E]-&gt;lock = 0;
        #pragma omp flush(array1[E]-&gt;lock)
     }
  </code></pre>
  
  <p>Is this theoretically safe? I am OK with ignoring elements that are being used by other threads because my algorithm will eventually visit them again. If my if fails, I move forward (I don't want to get stuck till the using thread releases the element).</p>