P
paolo.brandoli
Hello all,
Suppose that I have the following class "a" that returns a pointer to
a single instance of itself.
class a
{
public:
static a* getSingleInstance()
{
static a;
return &a;
}
};
The code is not thread safe, because several thread could call
getSingleInstance at the same time and the construction of a is not
guaranteed to be thread safe.
But if I add the following class "b", which call
a::getSingleInstance() in its constructor:
class b
{
public:
b()
{
a::getSingleInstance();
}
}
....and I add a static instance of b in some cpp file, like this:
static b;
this would still create the class "a" in the desidered order in case
it is needed by other static objects, but it would also create it in
case no other code require it. This would create the class before
main() starts and has the possibility to spawn other threads.
a::getSingleInstance() should be thread-safe from the second time it
is called, because the flag that controls the creation of the single
instance "a" doesn't need to be modified. I'm I right?
Would this make a::getSingleInstance() thread safe (supposing that
other static objects don't create any thread during their
construction)?
Any idea that would improve this?
Thanks in advance,
Paolo
Suppose that I have the following class "a" that returns a pointer to
a single instance of itself.
class a
{
public:
static a* getSingleInstance()
{
static a;
return &a;
}
};
The code is not thread safe, because several thread could call
getSingleInstance at the same time and the construction of a is not
guaranteed to be thread safe.
But if I add the following class "b", which call
a::getSingleInstance() in its constructor:
class b
{
public:
b()
{
a::getSingleInstance();
}
}
....and I add a static instance of b in some cpp file, like this:
static b;
this would still create the class "a" in the desidered order in case
it is needed by other static objects, but it would also create it in
case no other code require it. This would create the class before
main() starts and has the possibility to spawn other threads.
a::getSingleInstance() should be thread-safe from the second time it
is called, because the flag that controls the creation of the single
instance "a" doesn't need to be modified. I'm I right?
Would this make a::getSingleInstance() thread safe (supposing that
other static objects don't create any thread during their
construction)?
Any idea that would improve this?
Thanks in advance,
Paolo