Re: Thread safety
On Jun 7, 11:08 am, Gianni Mariani <gi3nos...@mariani.ws> wrote:
Jim Langston wrote:
...
2. Is the following thread safe:
void fn()
{
static Object o;
}
assuming multiple threds are active
Well, it is safe in this code, since you're not doing anything with o I
believe.
Only GCC (v4.0 or better) will work correctly (modulo a bug on some
platforms).
Actually, all of the compilers I have access to EXCEPT g++ work
correctly here. The difference is that g++ claims that this
code is conform to its contract, the others say it isn't. If
you write code that is not conform to the contract given by the
compiler, it's not the compiler which is wrong, it's your code.
G++ claims to offer more, but at least on my most common
platform (Sun Sparc, under Solaris), there is a bug in the
generated code, which means that they don't meet their own
guarantee.
In practice, the guarantee is usually worthless anyway, since as
Jim points out, you're going to use the object, and will need a
lock for that, so you might as well just take it before the
declaration, and be done with it. A more interesting case would
be if the static were const.
Construction of o is done when control first passes though the
definition. If two threads go through simultaneously, you can (and
often do) have construction happening twice. Not only that, it can also
fail if two separate static locals are initialized at the same time on
some platforms.
I don't know if any compilers other than GCC try to enforce
the initialize once rule for static locals in multi threaded
environments.
I suspect that most compilers are waiting 1) to see what the
standard will require here, and 2) to see what definition might
actually be useful. Having the compiler generate
synchronization code is pessimization (paying for something you
don't need) if I know that the first call will occur before
threading has started (often the case in my code), or if I need
a lock in the function anyway, in order to use the object. On
the other hand, having the compiler ensure whatever
synchronization necessary may be safer, especially where const
objects are concerned.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34