Damian
Damian

Reputation: 4651

Double-checked locking and the Singleton pattern

Does the Visual Studio 2015 compiler insert double-checked locking?

I would like do make my Singleton (GOF) pattern thread safe (lock-free).

Singleton& Singleton::getInstance() {
    static Singleton instance;
    return instance;
}

Is it possible to produce the assembler code and check?

Upvotes: 1

Views: 80

Answers (1)

MaciekGrynda
MaciekGrynda

Reputation: 703

You can access disassembly in Debug->Windows->Disassembly.

For class:

class S
{
public:
    static S& getInstance()
    {
        static S instance;
        return instance;
    }
};

You get disassembly:

47: 
48: class S
49: {
50: public:
51:     static S& getInstance()
52:     {
push        ebp  
mov         ebp,esp  
sub         esp,0C0h  
push        ebx  
push        esi  
push        edi  
lea         edi,[ebp-0C0h]  
mov         ecx,30h  
mov         eax,0CCCCCCCCh  
rep stos    dword ptr es:[edi]  
53:         static S instance;
54:         return instance;
mov         eax,offset instance (0D9471h)  
55:     }
pop         edi  
pop         esi  
pop         ebx  
mov         esp,ebp  
pop         ebp  
ret  

Upvotes: 2

Related Questions