I have the following class
class Singleton
{
private:
static Singleton *p_inst;
Singleton();
public:
static Singleton * instance()
{
if (!p_inst)
{
p_inst = new Singleton();
}
return p_inst;
}
};
Please do elaborate on precautions taken while implementing Singleton in multi-threaded environment .
In multi-threading that clause
is actually 3 separate actions. You are getting the value of
p_inst, setting the value ofp_instand writing the value ofp_inst. So get-set-write means that you need to put a lock aroundp_instotherwise you can have 2 threads which create aSingletonvalue that each thread uses.Here is how you can view the issue, assume that your
Singletonhas a mutable fieldval:You see? There’s 2 copies of a Singleton floating about, neither of which knows about the other. The third thread which checks on the
Singletonis only going to see the last assignment. But with locking, you can prevent multiple assignment and these types of problems.