Re: Are static array pointers thread safe?
On Thu, 29 Nov 2007 17:50:49 -0800 (PST), flowstudioLA@gmail.com wrote:
Can multiple threads safely use static array pointers as in the class
below? What are the dangers if not?
class foo{
static int (*a)[26][26];
void createArray();
void writeToArray(int a, int b, int c, int d);
int readFromArray(int a, int b, int c);
}
int (*foo::a)[26][26];
void foo:createArray(){
a = new int[26][26][26];
}
I take it your real code creates a dynamically-sized array? If not, and you
always call createArray, and you never assign another value to the pointer
"a", you should just use an actual array variable. Since you aren't
initializing the array contents, it won't even grow your executable, and
since it has static storage duration, there are no stack overflow issues to
worry about.
void foo:writeToArray(int a, int b, int c){
a[a][b][c] = d;
}
void foo::readFromArrat(int a, int b, int c){
return a[a][b][c];
}
You need to understand memory visibility rules to answer this question.
Threads created after you call createArray will observe the value
createArray wrote to "a". Threads created before createArray has been
called must use a mutex to reliably observe the value, and of course,
createArray must in that case synchronize on the same mutex as the threads.
That takes care of "a". What about *a? Your writeToArray and readFromArray
functions must use synchronization if multiple threads are to use them
concurrently; the issues are really no different than they were for "a".
--
Doug Harrison
Visual C++ MVP