1

I am trying to use openMP, and I have this one function that can never be run two times at the same time. In another world, this would not be a problem:

int foo(void){
 mutex->lock();
 ....
 mutex->release();
}

How can I achieve the same thing in OpenMP?

Werner Henze
  • 16,404
  • 12
  • 44
  • 69
Cheiron
  • 3,620
  • 4
  • 32
  • 63

1 Answers1

1

Use:

#pragma omp critical (CriticalSection1)
{
    // your stuff here
}

EDIT

I hope this is clearer:

int foo(void){
    //mutex->lock();
#pragma omp critical (CriticalSection_foo)
    {
        ....
    }
    //mutex->release();
}

EDIT 2

I extended the example to include named critical section, as advised by the commenters. The round brackets are necessary, see the Intel OMP documentation with an example.

Sven
  • 1,748
  • 1
  • 14
  • 14
  • So where do I put the int foo(void) part? Above the pragma? Under it? – Cheiron Oct 30 '13 at 12:56
  • Not at all. The "int foo(void)" part is your function declaration. Just edited my answer. – Sven Oct 30 '13 at 12:57
  • 2
    Wouldn't it be better to give a name for the critical region? As I read "All unnamed critical directives map to the same unspecified name.". – Werner Henze Oct 30 '13 at 13:00
  • @Werner: You could do that. It's optional. – Sven Oct 30 '13 at 13:09
  • 1
    I second @WernerHenze. In this particular case it is highly advisable not to use an unnamed critical section as it could lead to unwanted synchronisation with other completely unrelated portions of the code that also use unnamed critical sections. This is an orphaned construct and you have no idea how exactly the code that calls the function looks like. – Hristo Iliev Oct 30 '13 at 13:18
  • @HristoIliev I extended my example with named critical sections. – Sven Oct 30 '13 at 13:24