[ back to toc ]

Static variables in multithreaded code

Date: 2002/05/30 14:30

Q:
I am fairly new to C/C++. I am trying to have a few global variables
(maybe static?) including an STL list variable that will be used (items
added/deleted) withing multi threads. The OS is AIX 4.3 and the compilar
is g++ (GNU) 2.9.

How best can I do this? I mean should I explicitly define these global
varibles as 'static' (if so how do I do it?). Or should I use the 'extern'
keyword in defining these global varibles?

It'll be a great help if you can give me a code example on how to define
these global varibles according to your recommendation.

- *NAME-DELETED*
A:
The keyword static and extern have special meaning when using for
declaration of global variables.

Declaring a global variable 'static' means that the symbolic reference of
the variable (the variable name) will not get into the object file symbol
table and thus the variable can not be referenced from other source file
linked to the final executable. Other than this there is no other effect.
This can help you to use global variables that are local to some 'module'
implemented in a single source file.

The keyword 'extern' tells the compiler that the variable is declared
somewhere else. Thus if a variable is declared as 'extern' in each C
source file and not without this keyword then the linker will complain
that the variable is referenced but not defined. It has to be defined in
one of the source files.

I hope this will make these issues more clear.

Regards,
Peter
Q:
So if I declare a varible in one source file (in a global area) and use
the word 'extern' to reference it from other source files, I can
effectively use that variable as a global variable between all my
sourcefiles isn't it?

Also is it okay to use STL List class as one of these globals in a
multi-threading program? The Environment is AIX 4.3 with GNU C++ 2.9.

Thanks

- *NAME-DELETED*.

A:
>>>
So if I declare a varible in one source file (in a global area) and use
the word 'extern' to reference it from other source files, I can
effectively use that variable as a global variable between all my
sourcefiles isn't it?
<<<

No. You define the variable in ONE and only one file and it should not be
static.

You use 'extern' to *declare* the variable in another file. After the
declaration you can use the variable in that file. Not just every source
file, but rather only in those files that declare the variable. This can
effectively be done including a header file that declares the global
variable.

>>>
Also is it okay to use STL List class as one of these globals in a
multi-threading program? The Environment is AIX 4.3 with GNU C++ 2.9.
<<<

I do not know. I am not familiar with AIX or STL. Most probably yes.

Regards,
Peter

[ back to toc ]