[cpp-threads] Globals and Threads

jimmaureenrogers at att.net jimmaureenrogers at att.net
Sat Oct 15 21:54:04 BST 2005


I have been thinking about that little problem of globals related
to threads. Globals will need to be placed in a thread-shared memory
region, no matter how many threads are used in a C++ program.

My understanding is that this will result in a change in the way globals
are handled. 

While thinking about globals, I stumbled across the problem of static
locals. What is the implication when a function with local static variables
is called from several threads? This could result in race conditions if
one thread is updating the variable while the other reads from the
variable. Simply put, normal local static variables are not thread-safe.

Global variables are similarly not thread-safe.

Static data members provide a challenge similar to local static variables.
Separate instances of a class containing a static data member may be 
updated and read by separate threads. Static data members will need to be
placed in memory regions accessible to all threads. Read/write access
control (either through locks or non-locking mechanisms) would be useful
for static data members. Providing those mechnisms for non-threaded uses
would be somewhat inefficient, while not providing them for threaded uses
would result in incorrect programs.

Implicit protection for global and static regins could be provided by
a compiler when the compiler can detect the use of several thrads. The
biggest problem I see is the use of libraries. Compilers cannot determine
if a library will be used in a multi-threaded environment when the library
is compiled.

--
Jim Rogers
Colorado Springs, Colorado
U.S.A.



More information about the cpp-threads mailing list