[swift-dev] Thread safety of weak properties

Kevin Ballard kevin at sb.org
Sat Dec 12 02:29:54 CST 2015


On Sat, Dec 12, 2015, at 12:01 AM, Kevin Ballard wrote:
> Another possible fix is to just atomically load/store the Value pointer itself (assuming all platforms Swift runs on supports lock-free atomic pointers). This way if the object is deallocating, it would attempt an atomic CAS on the pointer to null it out, and only release the object if it wasn't already null. This means all writes to weak pointers now require an atomic write, but the benefit over the activity count / spinlock is reads don't have to perform an atomic write while the object is still alive, only an atomic read (although I'm not sure offhand if there's any practical performance difference there). And with this approach, it now becomes easy to make read/write and write/write safe. Whether this approach is worth doing depends on how many weak writes there are compared to weak reads (and offhand I don't have any idea there, except I do know I see an awful lot of code that looks like `weakRef?.foo(); weakRef?.bar(); weakRef?.baz()`).

I take it back, this is still unsafe because the object can get free'd while another thread is in the process of checking its refcount.

At the moment I'm leaning towards the activity count idea, though I'm not sure why you need a 16-byte CAS for that.

-Kevin


More information about the swift-dev mailing list