[Omp] static variables question

Klaas Vantournhout Klaas.Vantournhout at UGent.be
Sun Jan 7 07:23:25 PST 2007


Hi openmp users and developers,

I have a question regarding static variables which are declared in routines.

The OPENMP 2.5 specifications state that "Static variables declared in 
called routines in the region are shared.".  One way this seems like an 
obvious reasoning, but sometimes this causes problems, and I was 
wondering if there are solutions for this.

What I am thinking about are recursive functions which use static 
variables to obtain a meaningful result.  Those functions can not be 
used at all in parallelised regions there their result might be bogus, 
because when 2 functions run at the same time, they might corrupt the 
needed static variable.

To explain a bit further I have written a simple example here that 
multiplies two integers.

#include <iostream>
int multiply(int foo, int bar, bool foobar) {
         static int tmp = 0;
         if (foobar) tmp = 0;
         if (bar == 0 ) return 0;
         multiply(foo,bar-1,false);
         tmp += foo;
         return tmp;
}

int main(void) {
#pragma omp parallel for
         for (int i = 0; i < 100000; i += 10000) {
           int tmp = multiply(2,i,true);
#pragma omp critical
           std::cout << 2 << "x" << i << "=" << tmp <<std::endl;
         }
         return 0;
}

The result this gives after compilation is the following
[klaas at talvin10 openmp]$ ./a.out
2x0=0
2x10000=20000
2x20000=40000
2x30000=60000
2x40000=91904          << bogus
2x50000=113774         << bogus
2x60000=120000
2x70000=140000
2x80000=160000
2x90000=180000

As you see two results are wrong there threads mingled and corrupted the 
static int tmp variable.

So the question i have now, is the following.  Are there ways to solve 
this, without declaring threadprivate variables within the function or 
altering the function at all.  The reason I ask this is that I would 
like to use CLAPACK functions in parallelised loops, but they are 
swamped with static variables that cause during the run, serious memory 
problems.

With kind regards,

Klaas Vantournhout
-- 
"Several billion trillion tons of superhot
exploding hydrogen nuclei rose slowly above
the horizon and managed to look small, cold
and slightly damp."
	Douglas Adams - The Hitch Hickers
		Guide to the Galaxy


More information about the Omp mailing list