Your design does not work and this can be seen even without any understanding of what InterlockedCompareExchange
does. In fact, irrespective of the meaning of InterlockedCompareExchange
, your code is broken.
To see this, consider two threads arriving at the if
statement in getInstance
at the same time. Let's consider the three options for which branches they take:
- They both choose the second branch. Then you create two instances and your code no longer implements a singleton.
- They both choose the first branch. Then you never create an instance.
- One choose the first and the other chooses the second. But since there is no lock in the first branch, the thread that takes that route can read
AObject
before the other thread has written it.
Personally I'd use double-checked locking if I had to implement your getInstance
function.