Atomic-based lock for thread-safe use of elements

126 views Asked by At

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.

What I thought about doing was to create the following structure:

//try to use element E in array 1     

#pragma omp flush(array1[E]->lock)
   if(!array1[E]->lock){
      array1[E]->lock = 1;

      ...//use (either read, write or both) element

      array1[E]->lock = 0;
      #pragma omp flush(array1[E]->lock)
   }

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).

0

There are 0 answers