This is the mail archive of the
gcc-bugs@gcc.gnu.org
mailing list for the GCC project.
[Bug c++/13684] local static object variable constructed once but ctors and dtors called multiple times on same memory when called in multiple threads
- From: "rmerkert at alphatech dot com" <gcc-bugzilla at gcc dot gnu dot org>
- To: gcc-bugs at gcc dot gnu dot org
- Date: 15 Jul 2004 11:07:29 -0000
- Subject: [Bug c++/13684] local static object variable constructed once but ctors and dtors called multiple times on same memory when called in multiple threads
- References: <20040114172507.13684.evijaykumar@yahoo.com>
- Reply-to: gcc-bugzilla at gcc dot gnu dot org
------- Additional Comments From rmerkert at alphatech dot com 2004-07-15 11:07 -------
The cost of static local variables that are objects is actually quite expensive
in general because it requires testing whether or not the object has been
constructed. This is has nothing to do with thread safety. Using the
double-checked locking as is indicated allows for thread-safe initialization
that is no more costly than normal initialization with the exception of having
to acquire a mutex.
The code as indicated is not quite correct though, because initialization
requires a global mutex to avoid a deadlock.
So initialization needs to be done like this:
static volatile bool guard=true;
if (guard) {
if (__cxa_guard_acquire (&global_guard)) {
if (guard) {
// construct variable.
guard = false;
}
__cxa_guard_release (&global_guard)
}
}
Also, the guard boolean needs to be volatile.
--
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=13684