OpenMP 3.0 specifies that locks are no longer owned by threads, but by tasks. Once a lock is acquired, the current task owns it, and the same task must release it before task completion.
It looks like the omp_init_lock function is initializing the lock variable for setting/unsetting. This would include allocating any required memory used for the lock and setting the initial state to 'unlocked'. You should expect unpredictable results without proper initialization.
omp_get_num_threads() The omp_get_num_threads function returns the number of threads in the team currently executing the parallel region from which it is called. The function binds to the closest enclosing PARALLEL directive.
# pragma omp critical , (name) where name can optionally be used to identify the critical region. Identifiers naming a critical region have external linkage and occupy a namespace distinct from that used by ordinary identifiers.
You want the OMP_SET_LOCK
/OMP_UNSET_LOCK
functions:
https://hpc.llnl.gov/tuts/openMP/#OMP_SET_LOCK
Basically:
omp_lock_t writelock;
omp_init_lock(&writelock);
#pragma omp parallel for
for ( i = 0; i < x; i++ )
{
// some stuff
omp_set_lock(&writelock);
// one thread at a time stuff
omp_unset_lock(&writelock);
// some stuff
}
omp_destroy_lock(&writelock);
Most locking routines such as pthreads semaphores and sysv semaphores work on that sort of logic, although the specific API calls are different.
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.
#pragma omp critical
{
// write to file here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With