0

I have an array pointers.

Can I use mutex for lock and unlock? At the same time, Another thread run with the same and check matrix[h].

int **matrix;
matrix =new int[20];
for(int i=0; i<20; i++)
{
  matrix[i]= new int[20];
}

#pragma omp parallel for nowait
for(int h=0; h< 20; ++h)
{
   if(matrix[h].isfree()==true)
   {
     lock(matrix[h]);
     //do something...
     unlock(matrix[h]);
   }
   else
   {
     //that array matrix[h] is not free. 
     skip++;
   }
}
ph0123
  • 7
  • 6
  • You must provide more information about *"do something"*, otherwise we cannot actually properly answer the question! `matrix[h].isfree()` also makes no sense for an `int*`. Please create a [mcve], the current answers may mislead you. – Zulan Sep 19 '19 at 11:55

2 Answers2

0

You can use omp_lock_t mylock; for declaring the lock instead of pthread_mutex_t mylock; as you are using openmp. Then you can initialize the lock and use omp_set_lock(&mylock); to put a lock and omp_unset_lock(&mylock); to remove the lock. Have a look at this -> stackoverflow.com/questions/2396430/how-to-use-lock-in-openmp

Akshit
  • 424
  • 4
  • 15
0

If your intention is never to block the thread it suffices to use std::atomic_bool . Otherwise you should use std::lock_guard in combination with std::mutex .

Arne J
  • 415
  • 2
  • 9