Omkar
Omkar

Reputation: 831

OpenMP critical section vs locks

What is the difference between OpenMP locks and critical section? Are they just alternatives for each other? For example if I am writing to a same file using multiple files, should I use the locking or just the critical section before writing into the file?

Upvotes: 15

Views: 7359

Answers (1)

jepio
jepio

Reputation: 2281

Critical sections will most commonly use a lock internally, e.g.:

  • libgomp: source
  • libiomp:

    If the optional (name) is omitted, it locks an unnamed global mutex.

The OpenMP specification guarantees the following behaviour:

>

The critical construct restricts execution of the associated structured block to a single thread at a time

A critical section therefore serves the same purpose as acquiring a lock. The difference is that the low-level details are handled for you.

I would advise you to use critical whenever possible due to the simplicity. If you have separate blocks that need to be critical but don't interfere with each other give them names, and only if you need some behaviour that cannot be accommodated by the annotations, use explicit locking.

Upvotes: 14

Related Questions