Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>While as a general principle I agree with the point of view that creating objects in well defined order is preferable, from thread safety perspective the implementation posted in the question is safer than constructing the singleton object within getInstance. In the latter case unless the programmer explicitly use atomic operations, the contructor can, in theory be invoked more than once. Following is dis-assembly using VS2013 (debug with no optimizations) for x86 target for this code.</p> <pre><code>singleton* singleton::getInstance() { static singleton rc; return &amp;rc; } static singleton* getInstance() { 00E85820 push ebp 00E85821 mov ebp,esp 00E85823 push 0FFFFFFFFh 00E85825 push 0E89E6Eh 00E8582A mov eax,dword ptr fs:[00000000h] 00E85830 push eax 00E85831 sub esp,0C0h 00E85837 push ebx 00E85838 push esi 00E85839 push edi 00E8583A lea edi,[ebp-0CCh] 00E85840 mov ecx,30h 00E85845 mov eax,0CCCCCCCCh 00E8584A rep stos dword ptr es:[edi] 00E8584C mov eax,dword ptr ds:[00E8F000h] 00E85851 xor eax,ebp 00E85853 push eax 00E85854 lea eax,[ebp-0Ch] 00E85857 mov dword ptr fs:[00000000h],eax static singleton ref; 00E8585D mov eax,dword ptr ds:[00E8F330h] 00E85862 and eax,1 00E85865 jne singleton::getInstance+6Ch (0E8588Ch) 00E85867 mov eax,dword ptr ds:[00E8F330h] 00E8586C or eax,1 00E8586F mov dword ptr ds:[00E8F330h],eax 00E85874 mov dword ptr [ebp-4],0 00E8587B mov ecx,0E8F32Ch 00E85880 call singleton::singleton (0E810D2h) 00E85885 mov dword ptr [ebp-4],0FFFFFFFFh return &amp;ref; 00E8588C mov eax,0E8F32Ch } </code></pre> <p>dword ptr ds:[00E8F330h] is used as flag to check whether to call constructor or not.</p> <p>As expected , no atomic compare and exchange instructions are emitted by the compiler. Therefore, if thread B executes instruction at 00E8585D before thread A executes instruction 00E8586F, the constructor will be invoked by both. However, to see this in practice, we would probably need to use special test cases where multiple threads are spawned (on a multicore processor) and blocked on an event/semaphore, . Then signal the semaphore to release all thread at once, and hopefully we will see the constructor will be called more than once. The same applies if you do a new singleton() inside getInstance.</p> <p>This issue is not specific to singletons.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload