[swift-dev] Thread safety of weak properties
John McCall
rjmccall at apple.com
Tue Dec 15 20:53:57 CST 2015
> On Dec 15, 2015, at 6:27 PM, Kevin Ballard <kevin at sb.org> wrote:
> On Tue, Dec 15, 2015, at 06:12 PM, John McCall wrote:
>> So, just to complete the loop here: absent Darwin granting public and backwards-compatible access to an internal API, we need to write this in a way that falls back on using a heavyweight lock in the presence of contention. I’m fine with that being a global lock.
>
> Well, no, the activity count idea isn't a spinlock and is perfectly safe. It's actually basically a retain count, but it's protecting write access to the field rather than protecting an object.
I keep forgetting about that option; that would be better. And we can assert that the activity count of the target is zero in weakAssign / weakCopyAssign / weakTakeAssign because anything else would be a read/write race. weakCopyAssign and weakCopyInit will have to bump the activity count of the source during the unownedRetain.
>> Note that Darwin platforms need this to interoperate with the unknownWeak entrypoints.
>
> What does that interoperation look like?
The current implementation is in SwiftObject.mm, but it has nasty races with deallocation.. If we add an extra word to WeakReference, we can just use a specific bit pattern to indicate that the reference was last set to an ObjC pointer. The native implementation can assert that it never sees that pattern.
The compiler does have intrinsic knowledge of the size of a weak reference, but it is simple to update that when we have a runtime implementation we’re happy with.
John.
More information about the swift-dev
mailing list