"John Harrison" <jo*************@hotmail.com> wrote in message
news:be************@ID-196037.news.dfncis.de
"joe martin" <no@never.com> wrote in message
news:86********************************@4ax.com... Hey all,
For singleton code that looks like this:
class JoeClass
{
friend JoeClass &joeFunction();
private:
JoeClass() { someFunction();}
}
JoeClass &joeFunction()
{
static JoeClass jc;
return jc;
}
with multiple threads, JoeClass is being returned from joeFunction
without someFunction being called. To get it to work i had to put in
status flags in the constructor before and after someFunction() and
wait on them before returning in joeFunction... I don't understand
what is happening. Am I doing something wrong or is this a bug in
VC++ or something.
Thanks,
Joe
C++ doesn't have any support for threads. Presumably something like
this is happening
1) First thread enters joeFunction, starts construction of jc, marks
it as constructed but does not yet finish construction
2) Second thread enters joeFunction, sees jc marked as constructed so
exits immediately
3) First thread completes construction of jc.
VC++ is probably doing it this way to prevent multiple construction
of jc, in the event of the JoeClass constructer indirectly causing
joeFunction to be called again. But as you've found in the case of
multiple threads is can result in joeFunction returning without jc
being fully constructed.
Basically if you want threads in C++ you have to do it yourself. VC++
isn't doing anything wrong that I can see.
john
Section 6.7 p 4 of the standards says:
[after discussing some cases not relevant here]
Otherwise such an object is initialized the first time control passes
through its declaration; such an object is considered initialized upon the
completion of its initialization. If the initialization exits by throwing an
exception, the initialization is not complete, so it will be tried again the
next time control enters the declaration. If control re-enters the
declaration (recursively) while the object is being initialized, the
behavior is undefined. [Example:
int foo(int i)
{
static int s = foo(2*i); // recursive call - undefined
return i+1;
}
-end example]
If VC++ is marking the object as constructed before it is in fact
constructed, then this would seem to me to be in conflict with the
standard --- unless multi-threading can be seen as akin to a recursive call
in this respect.
The basic point remains, of course. The orginal joeFunction code is not
thread safe.
--
John Carson
1. To reply to email address, remove donald
2. Don't reply to email address (post here instead)