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?
11
votes
What are you writing to the file? Are you writing from each thread? Do you use tasks or parallel loops? Do you write from all threads? Do you have some code? Which language do you have in mind? (OpenMP supports Fortran, C and C++) Your question is very broad and hard to answer, you should narrow it.
– Vladimir F
OK i will just try a simple operation.I have taken a char buffer in c++ and while one thread is writing to this buffer i just want the other threads should not try to read or write into this buffer.Only one thread at a time should have the access to the buffer.It may read or write into that buffer..So shall I include writing in buffer under critical section or rather use locks
– Omkar
It really depends on the overall design of your code.
– Vladimir F
See stackoverflow.com/questions/17018965/openmp-lock-vs-critical/… and possibly others here on SO.
– High Performance Mark
1 Answers
12
votes
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 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.