How to use lock in OpenMP?

59,996

Solution 1

For the benefit of those coming after, using critical is another option. You can even make named critical sections.

For example:

#include <omp.h>

void myParallelFunction()
{
    #pragma omp parallel for
    for(int i=0;i<1000;++i)
    {

        // some expensive work 

        #pragma omp critical LogUpdate
        {
            // critical section where you update file        
        }

        // other work

        #pragma omp critical LogUpdate
        {
            // critical section where you update file      
        }
    }
} 

Edit: There's a great thread in the comments initiated by Victor Eijkhout. Summarizing and paraphrasing: In short critical locks a code segment. That can be overkill in more complex examples where all you want to do is lock a specific data item. It's important to understand this before you make a choice between the two methods.

Solution 2

#pragma omp critical
{
    // write to file here
}
Share:
59,996
Shailendra Kushwah
Author by

Shailendra Kushwah

Updated on July 19, 2021

Comments

  • Shailendra Kushwah
    Shailendra Kushwah almost 3 years

    I have two pieces of C++ code running on 2 different cores. Both of them write to the same file.

    How to use OpenMP and make sure there is no crash?