Synchronization
OpenMP will not check the data dependencies, data conflicts, race conditions, deadlocks, or code sequences for you. You have to deal with those problems by yourself. OpenMP can have some ways to solve it, but you can also give a better solution(e.g. partition the data properly).
Here we have a race condition problem in the OpenMP version:
Compile it and run it multiple times, you will found that your results will vary each time you run it. This is the effect of race condition.
How to solve it in OpenMP using the build-in solutions?
critical: Mutual exclusion, Only one thread at a time can enter a critical region.
After compiling and running multiple times, you will fount you can only get one answer "20000000", which is just what we want. (You will also find that the running time increases compared with the former one, it's normal.)
reduction(op:list): A local copy of each list variable is made and initialized depending on the "op". It will do calculation related with "op" after all the thread finish.
Try it by yourself! (You can also pay attention to the running time)
Notice that the C compilers for OpenMP also support*, -, &, |, ^, &&, ||
in reduction.
lock routines: just like lock like what you did in pThread.
Try it by yourself and compare the time using different methods!
OpenMP also has many other solutions to synchronization problems, such as barrier, master, single, ordered. You can Google them and get more information about them.
These examples are all usingfor
, can you solve synchronization problems not usingfor
?
Last updated