Protecting Updates of Shared Variables

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 2

Protecting Updates of Shared variables: The critical and atomic pragmas are supported by the OpenMP standard for

you to protect the updating of shared variables for avoiding data-race conditions. The code block enclosed by a critical section and an atomic pragma are areas of code that may be entered only when no other thread is executing in them. #pragma omp critical if ! max " new#value $ max % new#value & The named critical sections are used when more than one thread is competing for more than one critical resource.
#pragma omp critical(maxvalue) { if ( max < new_value ) max = new_value }

't is important to remember that entering nested critical sections runs the risk of deadlock. The following code example code shows a deadlock situation(
void dequeue(NOD !node) { #pragma omp critical (x) { node = node"#next$ } } void do_wor%(NOD !node) { #pragma omp critical (x) { node"#next"#data = fn&(node"#data)$ node = dequeue(node) } }

Thus) the do#work function could never complete. This is a deadlock situation. The simple way to fix the problem in the previous code is to do the inlining of the de*ueue function in the do#work function as follows( Deadlock free code:
void do_wor%(NOD !node) { #pragma omp critical (x) { node"#next"#data = fn&(node"#data)$

node = node"#next$ } }

't is sometimes you may re*uire that a statement in a high-level language complete in its entirety before a thread is suspended. +or example) a statement x,, is translated into a se*uence of machine instructions such as( load reg, [x]; add reg 1; store [x], reg; 't is possible that the thread is swapped out between two of these machine instructions. The atomic pragma directs the compiler to generate code toensure that the specific memory storage is updated atomically. The following code example shows a usage of the atomic pragma. int main!$ float y-.///01 int k) idx-.///01 #pragma omp parallel for shared!y) idx$ for ! k % /1 k " 2///1 k,,$ idx-k0 % k 3 .///1 y-idx-k00 % 2./1 & #pragma omp parallel for shared!y) idx$ for ! k % /1 k " 2///1 k,,$ #pragma omp atomic y-idx-k00 ,% 2./ 4 !k 3 .///$1 & return /1 & 5n expression statement that is allowed to use the atomic pragma must be with one of the following forms( x binop % exp x,, ,,x x6 --x 'n the preeding expressions) x is an lvalue expression with scalar type1 expr is an expression with scalar type and does not reference the ob7ect designed by x1 binop is not an overloaded operator and is one of ,) 4) -) 8) 9) : ) ; ) "") or << for the =8=,, language.

You might also like