5 ms·
If you have atomic swaps (hardware "lock-free"), the global shared instance pointer should be enough - since it either holds a valid pointer or it doesn't.
by vy8vWJlco 13y ago
If you have atomic swaps (hardware "lock-free"), the global shared instance pointer should be enough - since it either holds a valid pointer or it doesn't.
- limmeau 13y agoWhat do you swap into the pointer? A new instance?
- vy8vWJlco 13y agoIf the pointer is 0 through a normal test, you would allocate the resource and do a compare-and-swap to record the allocation if the pointer is still 0. As noted beside this comment, you might wind up allocating several times in parallel (which may be undesirable too), but you would never clobber an existing allocation or change the instance that is dispensed.
- jamesaguilar 13y agoNo, you don't want two threads trying to allocate the object at once. You still need a locked init.
- vy8vWJlco 13y agoYes, there would be an allocation race, so if you cannot accept allocating unnecessarily in a discardable/recoverable way (but also one that preserves the semantics of the singleton: one and only one instance returned over its life), you would still need a flag. Though you might instead use an "incomplete"/place-holder reference value to simulate the flag and prevent duplication of effort/wasting resources while the allocation happens - all in the space of the pointer.
- rbehrends 13y agoThat's not sufficient on its own (leaving aside the problem of multiple initialization). While compare and swap will likely have the necessary write barrier built in, you need a matching read barrier when accessing the object. I.e. reads could otherwise get re-ordered so that you see the pointer and the not-yet-initialized object at the same time.
- vy8vWJlco 13y agoRight. I was still thinking in terms of my thread-local-less model posted before when I wrote the above, which took for granted those barriers once past init.